If you create a regular javascript object using say var obj = {};
it will have the object prototype. Same goes for objects created using var obj = new MyClass();
Before Object.create
was introduced there was no way around this. However nowadays it's possible to create an object with no prototype (respectively null
as its prototype) using var obj = Object.create(null);
.
Why is this important? What advantages does it bring? Are there any real world use cases?
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) .
Null. In JavaScript null is "nothing". It is supposed to be something that doesn't exist. Unfortunately, in JavaScript, the data type of null is an object. You can consider it a bug in JavaScript that typeof null is an object.
It's a completely empty object (nothing inherited from any .prototype
including Object.prototype
), so you can be guaranteed that any property lookup will only succeed if the property was explicitly added to the object.
For example, if you want to store some data where you won't know the keys in advance, there's a possibility that a provided key will have the same name as a member of Object.prototype
, and cause a bug.
In those cases, you need to do an explicit .hasOwnProperty()
check to rule out unexpected inherited values. But if there's nothing inherited, your testing can be simplified to a if (key in my_object) {
test, or perhaps a simple truthy test if (my_object[key]) {
if appropriate.
Also, with no prototype chain, I would imagine that lookups of properties that turn out to not exist would be faster, since only the immediate object would need to be checked. Whether or not this pans out in reality (due to optimizations) would be determined with performance testing.
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