gpt4 book ai didi

javascript - 为什么 toString.call ('my string' ) 不同于 'my string' .toString(),或者,为什么 document.toString !== 'asd' .toString?

转载 作者:行者123 更新时间:2023-11-29 18:24:14 27 4
gpt4 key购买 nike

正在阅读 Underscore.js 以了解它的 is[String|Number|...] 方法是如何工作的,现在我很困惑。下划线:

toString.call(obj) == ['object ' + name + ']';

好吧,我可以的

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

但是

>>> 'my string'.toString()
"my string"

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

>>> document.toString === toString
true

>>> document.toString === 'asd'.toString
false

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

最佳答案

那是因为:

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.call(obj)

toString 方法中,this 现在引用obj。这将是等价的:

Object.prototype.toString.call(obj)

关于javascript - 为什么 toString.call ('my string' ) 不同于 'my string' .toString(),或者,为什么 document.toString !== 'asd' .toString?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15182623/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com