Object.create的用例(null) [英] Use cases for Object.create(null)
问题描述
据我所知,使用 Object.create(null)
会创建一个没有 proto
属性的对象(即 Object.getPrototypeOf(myObj)=== null
)但有人可以帮我理解一下这个用例是什么吗?
I understand that using Object.create(null)
creates an object which has no proto
property (i.e. Object.getPrototypeOf( myObj ) === null
) but can someone help me understand what are some of the use cases for this?
换句话说,为什么要创建一个完全为空的对象(即不从 Object.prototype
继承任何方法)?
In other words, why would you want to create an object that is completely empty (i.e. doesn't inherit any methods from Object.prototype
)?
推荐答案
在非常罕见的情况下,可能已将某些内容添加到 Object.prototype
In very rare instances where something may have been added to Object.prototype
Object.prototype.bar = 'bar';
使用对象可能更好> Object.create(null)
因为它不会继承这个,考虑
It may be better to create an Object with Object.create(null)
as it won't inherit this, consider
({}).bar; // bar
// vs
Object.create(null).bar; // undefined
这意味着您不必担心,例如,如果您使用过 for..in
loop
This means you don't have to worry for example if you've used a for..in
loop
此外,你可以使它失败 instanceof
tests
Furthermore, you can make it so you fail instanceof
tests
Object.create(null) instanceof Object; // false
这是因为 instanceof
是基本上是针对RHS测试原型链,并且没有这样的链。
This is because instanceof
is basically testing the prototype chain against the RHS, and there is no such chain.
这篇关于Object.create的用例(null)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!