在尝试默认行为时Object.toString()
函数,我注意到像下面这样的字符串连接可以预见地调用toString()
在目标对象上:
var x = { toString: () => "one" };
var y = { toString: () => "two" };
var output = 'x is ' + x + ' while y is ' + y;
console.log(output); // writes "x is one while y is two" to the console
然而,当toString()
在原型中被重写Number
and Boolean
, 例如。有必要“强制”toString()
调用以获得所需的输出:
Number.prototype.toString = () => "42";
Boolean.prototype.toString = () => "whatever you wish";
var a = 1;
console.log('The answer is ' + a); // writes "The answer is 1"
console.log('The answer is ' + a.toString()); // writes "The answer is 42"
var b = true;
console.log('Girl you know it\'s ' + b); // writes "Girl you know it's true"
console.log('Girl you know it\'s ' + b.toString()); // writes "Girl you know it's whatever you wish"
这在浏览器中是一致的(在 Chrome、Firefox 和 Edge 上测试过),所以我认为这是标准行为。它记录在哪里?是否有在字符串连接期间得到特殊处理的标准对象的列表?
JavaScript 可以在数字基元和数字对象之间自由转换。
如果你看一下的规则+操作员你会看到它说:
7 令 alprim 为 ToPrimitive(laval)。
and
9 设 rprim 为 ToPrimitive(rval)。
所以在处理的时候+
它将尝试使用对象上的原语。
然后它有字符串规则将原语转换为字符串。
数量 参见 7.1.12.1。
…然后描述了一个很长的特殊情况.
简而言之:
它将值转换为基元,然后具有将数字转换为字符串的特殊情况规则。
这意味着它不会将其视为对象或调用.toString
通常可以覆盖此类规则的方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)