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
)?
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.
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) .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With