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

2023-11-28

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

问题:

它是否与以下完全相同:

var p = {}

vs

var p2 = Object.create(null);

?


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

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

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


在 Chrome DevTools 中你可以看到Object.create(null)没有原型,而{} does.

Screenshot of DevTools console prompted with Object.create(null), which results in a completely empty object; and with {}, which results in an object shown to have a [[Prototype]] internal slot with the same properties as Object.prototype

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用Object.create(null)创建JS对象和{}一样吗? 的相关文章

随机推荐