以下是
JavaScript中的一个问题:
// 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]
为什么toString的结果与toString.call()不同?
更新
String.prototype.toString.call("foo"); // "foo" Object.prototype.toString.call("foo"); // [object String]
String.prototype.toString不是从原型链如下所示?
toString in String[not found] –> toString in String.prototype[not found]
06002
解决方法
String.prototype.toString覆盖Object.prototype.toString.它们不是相同的功能.
从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.)
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 “]“.
数组的行为类似,它们也覆盖了toString():
> [1,2].toString() "1,2"