我知道很多创建 JS 对象的方法,但我不知道 Object.create(null)
的方法。
问题:
是否完全一样:
var p = {}
对比
var p2 = Object.create(null);
?
最佳答案
它们不等价。 {}.constructor.prototype == Object.prototype
而 Object.create(null)
不继承任何东西,因此根本没有任何属性。
换句话说:默认情况下,javascript 对象继承自 Object,除非您显式地以 null 作为原型(prototype)创建它,例如:Object.create(null)
。
{}
将等同于 Object.create(Object.prototype)
。
在 Chrome Devtool 中,您可以看到 Object.create(null)
没有 __proto__
属性,而 {}
有。
关于javascript - 使用 Object.create(null) 创建 JS 对象是否与 {} 相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15518328/