实现说明
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));