← 中文资源

简体中文版本

valueOf 与 toString 决定对象如何转换

对象转原始值先看 valueOf 再看 toString:算术拿到数字,模板字符串拿到文本,两者都没有就落成 [object Object]。想清楚该参与运算还是展示,再决定写哪个。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

50
cost: 42 dollars
true
42 dollars
42
[object Object]!

实现说明

顶层就这几处状态: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