javascript – 为什么“foo”.toString()与toString.call(“foo”)不同?

前端之家收集整理的这篇文章主要介绍了javascript – 为什么“foo”.toString()与toString.call(“foo”)不同?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以下是 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.)

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 “]“.

数组的行为类似,它们也覆盖了toString():

> [1,2].toString()
  "1,2"
原文链接:https://www.f2er.com/js/154669.html

猜你在找的JavaScript相关文章