我希望一个对象在数字上下文中返回一个值,在字符串上下文中返回一个完全不同的值。以下不起作用。
foo = {
toString: function() { return "string" },
valueOf: function() { return 123 }
}
console.log(foo * 2) // got 246, fine
console.log("hi " + foo) // got "hi 123", want "hi string"
The 加法运算符 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Addition将使用内部抽象操作将两个操作数转换为基元ToPrimitive https://tc39.es/ecma262/#sec-toprimitive,然后,如果一个操作数是字符串,它将使用内部抽象操作ToString https://tc39.es/ecma262/#sec-tostring将两者都转换为字符串(注意:这与toString
用户态对象上的方法。)
结果是,添加Symbol.toPrimitive https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toPrimitive对于该语言,您现在可以实现您的目标:
const foo = {
[Symbol.toPrimitive](hint) {
switch (hint) {
case "string":
case "default":
return "string"
case "number":
return 123
default:
throw "invalid hint"
}
}
}
console.log(foo * 2) // 246
console.log("hi " + foo) // "hi string"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)