[英]valueOf function set to always return the same value
This: 这个:
% node
> var o = {valueOf: function() { return 5; } };
undefined
> o += 1;
6
> o
6
> o += 1;
7
> o
7
Why is o
value incremented if valueOf
always returns 5? 如果
valueOf
总是返回5,为什么o
值增加?
Starting from the situation where o
references the object as seen in the question: 从问题中看到
o
引用对象的情况开始:
var o = {valueOf: function() { return 5; } };
Then in the expression 然后在表达式中
o += 1;
what happens is: 发生的是:
o
is obtained as a number, via the call to .valueOf()
o
的值通过调用.valueOf()
获得为数字。 1
, giving 6
1
,得到6
o
o
Thus the variable o
, which once contained a reference to an object, now contains a number. 因此,曾经包含对对象的引用的变量
o
现在包含一个数字。
This is because you are assigning o = 5
, then you are incrementing the value, by doing += 1
and then you're querying the new value, which has now changed, increased by one, hence o = 6
. 这是因为您要分配
o = 5
,然后通过执行+= 1
来递增值,然后查询新值(现在已更改)增加了一个,因此o = 6
。 You're switching from object to a value when you're doing the first incrementation on the object! 在对象上进行第一次增量操作时,您正在从对象切换为值!
The valueOf()
method returns the primitive value of the specified object. valueOf()
方法返回指定对象的原始值。 What happened above is, 上面发生的是
o
is first assigned as object as below, 首先将
o
分配为以下对象,
var o = {valueOf: function() { return 5; var o = {valueOf:function(){return 5; } };
};
When you use o += 1;
当您使用
o += 1;
, you are here using o
as primitive
type and JavaScript calls the valueOf
method to convert an object
in to a primitive
type ,您在这里使用
o
作为primitive
类型,JavaScript调用valueOf
方法将object
转换为primitive
类型
Hence, o
is no longer object
but converted as primitive
type with value of 6 = 5 + 1
and started incremented with o += 1;
因此,
o
不再是object
而是转换为primitive
类型,其值为6 = 5 + 1
并以o += 1;
开始递增o += 1;
Hope it clarifies. 希望它能澄清。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.