Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

javascript - Why "foo".toString() is not the same as toString.call("foo")?

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]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...