OPTIONAL CHAINING 和 NULLISH COALESCING 运算符的组合未呈现预期结果

combination of OPTIONAL CHAINING and NULLISH COALESCING operator not rendering the expected result

我刚刚了解 可选链 无效合并 的组合。 这是 object

const restaurant = {
name_: 'Classico Italiano',
location: 'Via Angelo Tavanti 23, Firenze, Italy',
categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
mainMenu: ['Pizza', 'Pasta', 'Risotto'],

openingHours: {
    thu: {
        open: 12,
        close: 22,
    },
    fri: {
        open: 11,
        close: 23,
    },
    sat: {
        open: 0, // Open 24 hours
        close: 24,
    },
},
orderPizza(ing1, ing2) {
    console.log(`you have ordered your pizza with ${ing1} and ${ing2}`);
}};

当我试图检查该方法是否存在时,它正在打印出它们anyway.what我做错了吗?

console.log(restaurant.orderPizza?.('some', 'something') ?? 'no method exist');

可能 return 来自函数的值,否则它有一个未定义的值:

const restaurant1 = {
  name_: 'Classico Italiano',
  orderPizza(ing1, ing2) {
    return `you have ordered your pizza with ${ing1} and ${ing2}`;
  }
};

const restaurant2 = {
  name_: 'Other',
};

console.log(restaurant1.orderPizza?.('some', 'something') ?? 'no method exist');
console.log(restaurant2.orderPizza?.('some', 'something') ?? 'no method exist');