Object.prototype.valueOf() method

前端 未结 2 1513
滥情空心
滥情空心 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:26

    Let's look at what valueOf (that's a link) does:

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

    ToObject:

    String

    Create a new String object whose [[PrimitiveValue]] internal property is set to the value of the argument. See 15.5 for a description of String objects.

    In other words, it simply creates a new string object with the original value, i.e. new String('abc'). Now take a look at how that is displayed in your console, and you'll notice it's the same as the .valueOf.call result.

    Edit: This actually has more to do with what medium you use to view the answer. Chrome's and Firefox's dev tools display strings as their literal values (the string itself), but display string objects as if they were regular objects (by displaying their properties).

    A string is just an "array" of characters with some methods on them. So the representation {'0' : 'a', '1' : 'b', '2' : 'c'} means "a in the first position, b in the second, c in the third", which is the string you asked for.

    And as a final note, valueOf does not give [object ObjectName]. You may be referring to Object.prototype.toString

提交回复
热议问题