Object.prototype.valueOf() method

前端 未结 2 1514
滥情空心
滥情空心 2021-01-26 00:32
Object.prototype.valueOf.call(\"abc\")
{ \'0\': \'a\'
, \'1\': \'b\'
, \'2\': \'c\'
}
Object.prototype.valueOf.call(new String(\"abc\"))
{ \'0\': \'a\'
, \'1\': \'b\'
,          


        
2条回答
  •  遥遥无期
    2021-01-26 01:14

    Perhaps I've missed what the actual question is. Here is what ECMA-262 says:

    15.2.4.4 Object.prototype.valueOf ( )

    When the valueOf method is called, the following steps are taken:

    1. Let O be the result of calling ToObject passing the this value as the argument.

    2. If O is the result of calling the Object constructor with a host object (15.2.2.1), then

      a. Return either O or another value such as the host object originally passed to the constructor. The specific result that is returned is implementation-defined.

    3. Return O.

    In the expression:

    Object.prototype.valueOf.call("abc")
    

    Object.prototype.valueOf is being called with a string primitive as this. So at step 1, it is converted using the internal ToObject method.

    If passed a value of Type String (which "abc" is) ToObject will return a String object.

    Step 2 is irrelevant since the object is not a host object (it's a native object).

    Step 3 returns the object created by toObject.

    So test it:

    var x = Object.prototype.valueOf.call("abc");
    
    alert(typeof x); // object
    

    typeof returns object because the resulting value is a String object (a nice quirk of the typeof operator). You can go further:

    typeof x.match; // function
    x.constructor;  // function String() {[native code]}
    alert(x); // abc
    

    All consistent with the returned value being (a reference to) a String object.

提交回复
热议问题