gpt4 book ai didi

javascript - Object() 构造函数中内置的特殊行为

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

我正在读一本书,上面写着:

The Object() constructor has even more special behavior built into it. If you pass a more specific native object type as the parameter to the Object() constructor, it will actually type-detect and return the proper native object type, constructed automatically.

例如,

new Object("foo") will result the same as if you called new String("foo").

这两件事怎么可能是一样的。

但是

alert(new Object("foo") === new String("foo"));  // false

作者上面这句话到底是什么意思(new Object("foo") 将得到相同的结果...)?

最佳答案

在 JavaScript 中,不能使用 === 来比较对象。其作用是检查两者是否是相同的对象(而不是它们是否具有相同的值)。

该段落的内容如下:

new Object("foo") => new String("foo")
new Object(3) => new Number(3)
new Object(true) => new Boolean(true)
new Object([]) => new Array()

因此,它不是返回一个对象,而是计算出您传递给它的内容并返回一个类型的对象。

没有任何理由这样做。您不应该执行 new Object("foo")new String("foo"),而应该执行 "foo"

这是 native 类型:

new Object() => {}
new Array() => []
new String('foo') => 'foo'
new Number(3) => 3
new Boolean(true) => true

关于javascript - Object() 构造函数中内置的特殊行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32654681/

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