通过Object.create(null)语法创建的对象与通过{}语法创建的对象之间是否有区别?
从节点V5.6.0REPL:
> var a = Object.create(null)
undefined
> var b = {}
undefined
> a == b
false
> a.prototype
undefined
> b.prototype
undefined发布于 2016-05-26 22:13:44
由Object.create(null)生成的对象完全是空的--它们不会从Object.prototype继承任何东西。
空对象就行了。
在下面的示例中,我将检查toString的属性
var fromNull = Object.create(null);
console.log(typeof fromNull.toString);
var emptyObject = {};
console.log(typeof emptyObject.toString);
发布于 2016-05-26 22:13:10
是有区别的。
使用{},您可以创建一个原型为Object.prototype的对象。但是,执行Object.create(null)创建了一个原型为null的对象。
表面上看,它们似乎是相同的,但在后一种情况下,您不会继承附加到对象原型的基本函数。
var objPrototype = {};
console.log(objPrototype.toString());
var nullPrototype = Object.create(null);
console.log(nullPrototype.toString());
https://stackoverflow.com/questions/37471799
复制相似问题