Confusion regarding the Object.prototype.valueOf () method

I recently read an article on Object.prototype.valueOf () in MDN and I feel that they have something completely wrong saying:

The method valueOf()returns the primitive value of the specified object.

I mean, this sentence makes sense if we are talking about more specific versions of this method, for example String.prototype.valueOf(), which is closer in the prototype chain and therefore will be called instead of the method Object.prototypewhen the valueOfobject method is called String. In this case, the internal algorithm will be executed thisStringValueand the value of the internal property of the [[StringData]]object will be returned , that is, the return value of the primitive string. Thus, it will really be a conversion from an object to a primitive value.

But, as I understand it, the method valueOf Object.prototypeworks exactly the opposite way, calling the internal method ToObject.

Now, if Object.prototype.valueOf()called for a simple object, it will call ToObject, passing this method value, which points to the object itself, in which case ToObjectit will simply return a reference to the object, which is displayed toString()as [object Object].

Suppose we would redefine a value String.prototype.valueOf()using a related method Object.prototype, for example, and then create an object Stringby calling the constructor. - If we now call valueOf(), we will get the object in the reverse order, and NOT the primitive string value that we passed as an argument. There's just ToObjectin Object.prototype.valueOf(), no conversion from an object to a primitive value, as far as I can see.

So, I understood it correctly, and they are mistaken, or I did not understand it?

+4
3

valueOf() .

, MDN , . , valueOf. ( "" ):

valueOf() , , .

MDN .

:

valueOf- , , , .

, .

, . , valueOf , .

, " "

, .

+2

Object.prototype.valueOf , , . , , , valueOf() .

, , " " .

+1

, " " , , .

, " ",

, . : . :

OrdinaryToPrimitive O , :

  • Assert: Type (O) - Object

  • : () - "", "".

  • "string", Let methodNames be "toString", "valueOf" ".

  • Else, " ValueOf "," toString "".

...

III. () , .

  1. TypeError.

Of course, there is no guarantee that the implementation valueOfactually returns a primitive value, but what this method is for. And even Object.prototype.valueOfactually it will be called to convert the object to a primitive value if there is no other implementation in the prototype chain. This will not work, as you noticed, but it will still be called.

You can try it yourself:

var myObject = {
      valueOf: function() {
        console.log('valueOf');
        return this;
      },
      toString: function() {
        console.log('toString');
        return this;
      }
    };
 
1 + myObject;
Run codeHide result

It will be printed:

valueOf
toString
Uncaught TypeError: Cannot convert object to primitive value
0
source

Source: https://habr.com/ru/post/1617529/


All Articles