Use cases of Object.create (null)?

If you create a regular javascript object using say var obj = {}; It will have a prototype object. The same goes for objects created with var obj = new MyClass(); Before Object.create was introduced, this was not. However, it is currently possible to create an object without a prototype (respectively null as its prototype) using var obj = Object.create(null); .

Why is it important? What benefits does it bring? Are there any use cases in the real world?

+8
javascript null prototype
source share
2 answers

This is a completely empty object (nothing is inherited from any .prototype inclusing Object.prototype ), so you can be sure that any property search will succeed only if the property has been explicitly added to the object.

For example, if you want to save some data in which you will not know the keys in advance, there is a chance that the provided key will have the same name as the Object.prototype member and cause an error.

In these cases, you need to do an explicit .hasOwnProperty() check to rule out unexpected inherited values. But if nothing is inherited, your testing can be simplified to the if (key in my_object) { test, or perhaps a simple truthful if (my_object[key]) { test, if necessary.

In addition, without a prototype chain, I would suggest that searching for properties that, as it turns out, do not exist, would be faster, since only the closest object would need to be checked. Regardless of whether it will be performed in reality (due to optimization), performance testing will be determined.

+9
source share

The only difference between creating an object with {} and Object.create(null) is that the prototype of the object will not be inherited.

This means that any of the methods that we usually assume we can call on any object will not exist, for example toString and valueOf . A list of them can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype

In terms of performance, creating an object simply with {} is actually much faster, so unless you specifically can perform functions in the Object prototype, you should not create objects this way.

http://jsperf.com/null-vs-empty-object-performance

0
source share

All Articles