Here is a question in JavaScript below:
// Tested via Google Chrome console.
var toString = Object.prototype.toString;
"foo".toString(); // "foo"
toString.call("foo"); // [object String]
[].toString(); // ""
toString.call([]); // [object Array]
{}.toString(); // syntax error
toString.call({}); // [object Object]
Why the result of toString is different with toString.call() ?
UPDATED
String.prototype.toString.call("foo"); // "foo"
Object.prototype.toString.call("foo"); // [object String]
Is String.prototype.toString not from the prototype chain like below?
toString in String[not found] --> toString in String.prototype[not found]
--> toString in Object.prototype[found]
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:
- Let O be the result of calling ToObject passing the this value as the argument.
- Let class be the value of the [[Class]] internal property of O.
- 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"
>>> String.prototype.toString.call("foo")
"foo"
Object is not the same thing as a String.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With