gpt4 book ai didi

javascript - 使用Object.create(null)创建JS对象和{}一样吗?

转载 作者:太空宇宙 更新时间:2023-11-04 01:39:30 25 4
gpt4 key购买 nike

我知道很多创建 JS 对象的方法,但我不知道 Object.create(null) 的方法。

问题:

是否与以下内容完全相同:

var p = {}

对比

var p2 = Object.create(null);

最佳答案

它们并不等同。 {}.constructor.prototype == Object.prototypeObject.create(null) 不继承任何东西,因此根本没有属性。

换句话说:JavaScript 对象默认继承自 Object,除非您明确使用 null 作为原型(prototype)创建它,例如:Object.create(null)

{} 相当于 Object.create(Object.prototype)

<小时/>

在 Chrome Devtool 中,您可以看到 Object.create(null) 没有 __proto__ 属性,而 {} 有。

enter image description here

关于javascript - 使用Object.create(null)创建JS对象和{}一样吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53384490/

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