← 中文资源

简体中文版本

Symbol.toPrimitive 主导对象转换

Symbol.toPrimitive 决定对象转原始值的入口:hint 为 string 时先于 toString,number/default 时先于 valueOf,同一个对象在不同上下文里会得到不同结果。

阅读英文原文

实现说明

money、plain 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 直接运行文件,输出会带上标签,比如 hint:、String(money) :、unary plus :——输出的每一行都能指回产生它的那次调用。

常见问题

运行前要先安装什么?

什么都不用额外装——运行时自带了代码所需的一切。 文件的状态由几个模块级绑定持有:money、plain。

核心语句

return hint === 'string' ? '¥' + this.cents / 100 : this.cents;
return 'seven';

代码示例

// object-to-primitive conversion consults Symbol.toPrimitive first: the hint is 'string' | 'number' | 'default'
const money = {
  cents: 1250,
  [Symbol.toPrimitive](hint) {
    console.log('hint:', hint);
    return hint === 'string' ? '¥' + this.cents / 100 : this.cents;
  },
};

console.log('String(money) :', String(money)); // hint string
console.log('unary plus    :', +money); // hint number
console.log('template      :', `${money}`); // template literals run ToString: hint string
console.log('money + 50    :', money + 50); // arithmetic uses default

// without Symbol.toPrimitive the hint picks valueOf or toString:
// the + operator uses default and tries valueOf first; template literals and String() use string and try toString first
const plain = {
  valueOf() {
    return 7;
  },
  toString() {
    return 'seven';
  },
};
console.log('plain template:', `${plain}`);
console.log('plain + 1     :', plain + 1);
console.log('String(plain) :', String(plain));