Why “foo”.toString() is not the same as toString.call(“foo”)?

后端 未结 3 2081
长发绾君心
长发绾君心 2020-12-05 12:22

Here is a question in JavaScript below:

// Tested via Google Chrome console.
var toString = Object.prototype.toString;

"foo".toString(); // "f         


        
相关标签:
3条回答
  • 2020-12-05 12:28
    >>> String.prototype.toString.call("foo")
    "foo"
    

    Object is not the same thing as a String.

    0 讨论(0)
  • 2020-12-05 12:41

    String.prototype.toString overrides Object.prototype.toString. They are not the same function.

    From the specification of String.prototype.toString:

    Returns this String value. (Note that, for a String object, the toString method happens to return the same thing as the valueOf method.)

    And Object.prototype.toString:

    When the toString 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. Let class be the value of the [[Class]] internal property of O.
    3. Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".

    Arrays behave similar, they also override toString():

    > [1,2].toString()
      "1,2"
    
    0 讨论(0)
  • 2020-12-05 12:46

    The global toString function is different to the object.toString() function. According to this source, the global toString function is not very well defined, and thus badly implemented across different browsers. Essentially it provides functionality similar to the typeof operator.

    0 讨论(0)
提交回复
热议问题