用Object.create(null)创建JS对象? [英] Creating JS object with Object.create(null)?
问题描述
我知道很多创建JS对象的方法,但我不知道 Object.create(null)
的一个。
I know a lot of ways to create JS objects but I didn't know the Object.create(null)
's one.
问题:
与以下内容完全相同:
var p = {}
vs
var p2 = Object.create(null);
?
推荐答案
我认为它们并不等同。如果我没有错, {}。constructor.prototype == Object.prototype
而 Object.create(null)
不会从任何地方继承,因此根本没有属性。
I think they are not equivalent. If I'm not mistaking, {}.constructor.prototype == Object.prototype
while Object.create(null)
doesn't inherit from anywhere and thus has no properties at all.
换句话说:默认情况下,javascript对象从Object继承,除非你明确创建它指定null作为其原型,如 Object.create(null)
。
In other words: A javascript object inherits from Object by default, unless you explicitly create it specifying null as its prototype, as in Object.create(null)
.
{}
将改为等于 Object.create(Object.prototype)
。
在Chrome Devtool中你可以看到 Object.create(null)
没有 __ proto
哪个 {}
有。
In Chrome Devtool you can see that Object.create(null)
have no __proto
which {}
have.
这篇关于用Object.create(null)创建JS对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!