最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Use cases for Object.create(null) - Stack Overflow

programmeradmin0浏览0评论

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?

In other words, why would you want to create an object that is pletely empty (i.e. doesn't inherit any methods from Object.prototype)?

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?

In other words, why would you want to create an object that is pletely empty (i.e. doesn't inherit any methods from Object.prototype)?

Share Improve this question edited Dec 27, 2013 at 15:29 Liam 29.8k28 gold badges138 silver badges202 bronze badges asked Dec 27, 2013 at 15:28 wmockwmock 5,5025 gold badges43 silver badges62 bronze badges 1
  • 1 It's not really that useful, but in some cases where stuff have been added to the prototype chain, you might not want that in your object. In other cases, you'd like to use keys such as valueOf or toString, but then you have a problem, as they are already inherited from Object, unless you create an object that does not inherit those properties etc. – adeneo Commented Dec 27, 2013 at 15:39
Add a ment  | 

2 Answers 2

Reset to default 7

In very rare instances where something may have been added to Object.prototype

Object.prototype.bar = 'bar';

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

This means you don't have to worry for example if you've used a for..in loop

Furthermore, you can make it so you fail instanceof tests

Object.create(null) instanceof Object; // false

This is because instanceof is basically testing the prototype chain against the RHS, and there is no such chain.

You can use such an object for a key-value map. Without the prototype chain, you can be sure that things like .toString() do not unwittingly exist on the object. That means you can incautiously access properties on it, and you can use the in operator instead of Object.prototype.hasOwnProperty.call.

发布评论

评论列表(0)

  1. 暂无评论