我正在研究 JavaScript 中的对象到字符串的转换。所有对象都继承两个转换函数 - toString()
和valueOf()
。当 JavaScript 尝试将对象转换为字符串时,它会搜索 toString()
实现然后为 valueOf()
执行。所以我覆盖了 toString()
和valueOf()
这样:
var obj = {
x: 10,
y: 20,
toString: function() {
return "x = " + this.x + ", y = " + this.y;
},
valueOf: function() {
return this.x + ", " + this.y;
}};
将对象文字与字符串连接起来:
console.log("hello " + obj);
输出:hello 10, 20
输出不应该是:hello x = 10, y = 20
?
感谢任何帮助。
最佳答案
在console.log("hello "+ obj);
中,对obj
进行类型转换的运算符是+
,称为加法运算符。
在加法运算符中,每个参数都被转换为没有类型提示的原始值,而不是转换为字符串。当将对象转换为没有类型提示的基元时,将使用 valueOf
方法(如果可用)。仅当 valueOf
不可调用或返回非原始值时,才会使用 toString
。如果 valueOf
和 toString
都返回非原始值,则会引发 TypeError
。
引用规范:
http://es5.github.com/#x11.6.1
11.6.1 The Addition operator ( + )
1) Let lref be the result of evaluating AdditiveExpression.
2) Let lval be GetValue(lref).
3) Let rref be the result of evaluating MultiplicativeExpression. 4) Let rval be GetValue(rref). 5) Let lprim be ToPrimitive(lval).
6) Let rprim be ToPrimitive(rval).
7) If Type(lprim) is String or Type(rprim) is String, then
...NOTE 1 No hint is provided in the calls to ToPrimitive in steps 5 and 6.
9.1 ToPrimitive
...
Object - Return a default value for the Object. The default value of an object is retrieved by calling the [[DefaultValue]] internal method of the object, passing the optional hint PreferredType. The behaviour of the [[DefaultValue]] internal method is defined by this specification for all native ECMAScript objects in 8.12.8.
http://es5.github.com/#x8.12.8
8.12.8 [[DefaultValue]] (hint)
When the [[DefaultValue]] internal method of O is called with no hint, then it behaves as if the hint were Number, unless O is a Date object (see 15.9.6), in which case it behaves as if the hint were String.
...
When the [[DefaultValue]] internal method of O is called with hint Number, the following steps are taken:
1) Let valueOf be the result of calling the [[Get]] internal method of object O with argument "valueOf".
2) If IsCallable(valueOf) is true then,
- Let val be the result of calling the [[Call]] internal method of valueOf, with O as the this value and an empty argument list.
- If val is a primitive value, return val.
...
关于javascript - JavaScript 中的对象到字符串转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15038908/