为什么“foo”.toString()与toString.call(" foo")不同? [英] Why "foo".toString() is not the same as toString.call("foo")?
问题描述
以下是JavaScript中的问题:
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]
为什么toString的结果与toString.call()不同?
Why the result of toString is different with toString.call() ?
更新
String.prototype.toString.call("foo"); // "foo"
Object.prototype.toString.call("foo"); // [object String]
String.prototype.toString是不是来自原型链,如下所示?
Is String.prototype.toString not from the prototype chain like below?
字符串中的toString [未找到] - > String.prototype中的toString [未找到]
toString in String[not found] --> toString in String.prototype[not found]
--> toString in Object.prototype[found]
推荐答案
String.prototype.toString
覆盖 Object.prototype.toString
。它们的功能不同。
String.prototype.toString
overrides Object.prototype.toString
. They are not the same function.
来自规范 String.prototype.toString
:
返回此String值。 (注意,对于String对象, toString 方法会返回与 valueOf 方法相同的内容。)
Returns this String value. (Note that, for a String object, the toString method happens to return the same thing as the valueOf method.)
当 toString 方法是调用,采取以下步骤:
When the toString method is called, the following steps are taken:
- 让 O 成为调用ToObject传递的结果这个值作为参数。
- 让 class 成为 O 。
- 返回字符串值,该值是连接三个字符串 [object , class 和<的结果strong>] 。
- 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()
:
Arrays behave similar, they also override toString()
:
> [1,2].toString()
"1,2"
这篇关于为什么“foo”.toString()与toString.call(" foo")不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!