当对象添加到数字时,为什么JS调用`toString`方法 [英] Why does JS call `toString` method when object is added to a number
问题描述
我知道当JS尝试将对象表示为原始对象时,它会在对象上调用 valueOf
方法。但是今天我发现在同样的情况下它也会调用 toString()
方法:
I know that when JS tries to represent an object as primitive, it calls valueOf
method on an object. But today I found out that it also calls toString()
method in the same situation:
var o = {};
o.toString = function() {return 1};
1+ o; // 2
为什么?如果我添加 valueOf
方法,则不会调用 toString
。
Why? If I add valueOf
method then toString
is not called.
推荐答案
这一切都取决于提示。
当你使用 1 + o
这是一个数字提示,因为 +
操作数所以它肯定会在 toString
之前使用 valueOf
。
it all depends on the Hint.
when you use 1 + o
it is a number Hint because of the +
operand so it would definitely use valueOf
before toString
.
如果提示是字符串,然后 toString
在 valueOf
之前使用。例如,尝试 [o,o] .join(=)
If the hint is String, then toString
is used before valueOf
. for example try ["o",o].join("=")
所有这些将是:
var o = {};
o.toString = function() {return 1};
o.valueOf= function(){return 2};
1 + o; // 1+2=3 ==> it takes valueOf value
["o",o].join("") //o1 ==> it takes toString value
这篇关于当对象添加到数字时,为什么JS调用`toString`方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!