Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use cases for Object.create(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?

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)?

like image 480
wmock Avatar asked Dec 27 '13 15:12

wmock


People also ask

Which of the following will create an empty object?

New Keyword. The Object constructor creates an object wrapper for a given value. If the value is null or undefined , it will create and return an empty object.

What is object create null?

prototype while Object. create(null) doesn't inherit from anything and thus has no properties at all. 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) .


1 Answers

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.

like image 196
Paul S. Avatar answered Sep 18 '22 15:09

Paul S.