使用Object.create(null)创建JS对象是否与{}相同? [英] Is creating JS object with Object.create(null) the same as {}?
问题描述
我知道很多创建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.
问题:
是否与以下内容完全相同:
is it exactly the same as:
var p = {}
vs
var p2 = Object.create(null);
?
推荐答案
它们并不等效. {}.constructor.prototype == Object.prototype
,而 Object.create(null)
不继承任何东西,因此根本没有属性.
They are not equivalent. {}.constructor.prototype == Object.prototype
while Object.create(null)
doesn't inherit from anything and thus has no properties at all.
换句话说:默认情况下,除非您以null为原型明确创建它,否则javascript对象将从Object继承,例如: Object.create(null)
.
In other words: A javascript object inherits from Object by default, unless you explicitly create it with null as its prototype, like: Object.create(null)
.
{}
等效于 Object.create(Object.prototype)
.
在Chrome Devtool中,您可以看到 Object.create(null)
没有 __ proto __
属性,而 {}
有.
In Chrome Devtool you can see that Object.create(null)
has no __proto__
property, while {}
does.
这篇关于使用Object.create(null)创建JS对象是否与{}相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!