Javascript 为什么toString.call(';我的字符串';)不同于';我的字符串';。toString(),或者,为什么document.toString!==';asd';。toString?

Javascript 为什么toString.call(';我的字符串';)不同于';我的字符串';。toString(),或者,为什么document.toString!==';asd';。toString?,javascript,Javascript,我正在阅读下划线.js以了解它的是如何使用[String | Number |…]方法的,现在我感到困惑。下划线的作用是: toString.call(obj) == ['object ' + name + ']'; 好吧,我能做到 >>> toString.call('my string') "[object String]" 但是 我在这里迷路了!在我接到的第一个电话中: >>> document.toString === toString true

我正在阅读下划线.js以了解它的
是如何使用[String | Number |…]
方法的,现在我感到困惑。下划线的作用是:

toString.call(obj) == ['object ' + name + ']';
好吧,我能做到

>>> toString.call('my string')
"[object String]"
但是

我在这里迷路了!在我接到的第一个电话中:

>>> document.toString === toString
true

所以,我很困惑。我没想到会有这种行为。

那是因为:

document.toString === Object.prototype.toString
它实现了最基本的
toString
,类似于:

'[object ' + (typeof this) + ']';
这与只输出字符串本身的
String.toString()
非常不同,即:

> String.prototype.toString.call('hello world')
"hello world"
Array.toString()
,输出逗号分隔的值字符串

> Array.prototype.toString.call([1,2,3])
"1,2,3"
使用
.call()

为了实现这一点,他们基本上通过使用
.call()
在对象上应用
toString()

toString
方法中,
现在指的是
obj
。这相当于:

Object.prototype.toString.call(obj)
那是因为:

document.toString === Object.prototype.toString
它实现了最基本的
toString
,类似于:

'[object ' + (typeof this) + ']';
这与只输出字符串本身的
String.toString()
非常不同,即:

> String.prototype.toString.call('hello world')
"hello world"
Array.toString()
,输出逗号分隔的值字符串

> Array.prototype.toString.call([1,2,3])
"1,2,3"
使用
.call()

为了实现这一点,他们基本上通过使用
.call()
在对象上应用
toString()

toString
方法中,
现在指的是
obj
。这相当于:

Object.prototype.toString.call(obj)

为了澄清,我认识到
“一个字符串”。toString()
应该在逻辑上返回
“一个字符串”
。但这似乎与执行
toString.call(“字符串”)
时发生的情况相冲突。为什么您会认为两个不同的函数具有相同的行为?仅仅因为它们都被称为
toString
,并不意味着它们应该做相同的事情…@Xymostech:我猜它们都是从
Object.prototype.toString
继承的。我没有想到会有多个
toString
的实现。特别是因为
String.toString()
几乎不考虑逻辑命令,如果您愿意,这是一个“毫无价值”的无操作。为了澄清,我认识到
“一个字符串”。toString()
应该在逻辑上返回
“一个字符串”
。但这似乎与执行
toString.call(“字符串”)
时发生的情况相冲突。为什么您会认为两个不同的函数具有相同的行为?仅仅因为它们都被称为
toString
,并不意味着它们应该做相同的事情…@Xymostech:我猜它们都是从
Object.prototype.toString
继承的。我没有想到会有多个
toString
的实现。特别是因为
String.toString()
几乎是不顾逻辑命令的——如果你愿意的话,这是一个“毫无价值”的无操作。谢谢@Jack。我一直在寻找你最后写的那个等价物,但找的地方不对。现在这有道理了。谢谢@Jack。我一直在寻找你最后写的那个等价物,但找的地方不对。这是有道理的。