实现说明
顶层就这几处状态:price、plain。
模块级对象字面量,键名固定:tag。
常见问题
除了语言运行时还需要什么准备?
什么都不需要——语言运行时是唯一要求。 跨调用保留的状态放在这些顶层绑定里:price、plain。
代码示例
// Objects convert through valueOf before toString; the operation's hint picks
// which one runs, and Symbol.toPrimitive (if defined) comes before both.
const price = {
valueOf() { return 42; },
toString() { return '42 dollars'; },
};
console.log(price + 8); // hint default/number: valueOf wins -> 50
console.log(`cost: ${price}`); // hint string: toString wins
console.log(price == 42); // loose equality converts the object to 42
console.log(String(price)); // explicit String(): always toString
console.log(Number(price)); // explicit Number(): valueOf
// Objects with neither hook fall through to the default toString
const plain = { tag: 'cpu' };
console.log(plain + '!'); // "[object Object]!" - the classic surprise