简体   繁体   English

valueOf函数设置为始终返回相同的值

[英]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: 发生的是:

  1. The value of o is obtained as a number, via the call to .valueOf() o的值通过调用.valueOf()获得为数字。
  2. That value is added to 1 , giving 6 该值加到1 ,得到6
  3. That result is assigned to the variable 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, 上面发生的是

  1. o is first assigned as object as below, 首先将o分配为以下对象,

    var o = {valueOf: function() { return 5; var o = {valueOf:function(){return 5; } }; };

  2. 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类型

  3. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM