It is well-known that declaring objects with JSON notation makes them “inherit” from (or, more precisely, to be built like) the base Object:
myobj={a:1, b:2};
which is nearly equivalent to myobj = Object.create(Object); myobj.a=1; myobj.b=2;
and than:
Object.getPrototypeOf(myobj)
prints the following:
Object
__defineGetter__: function __defineGetter__() { [native code] }
__defineSetter__: function __defineSetter__() { [native code] }
__lookupGetter__: function __lookupGetter__() { [native code] }
__lookupSetter__: function __lookupSetter__() { [native code] }
constructor: function Object() { [native code] }
hasOwnProperty: function hasOwnProperty() { [native code] }
isPrototypeOf: function isPrototypeOf() { [native code] }
propertyIsEnumerable: function propertyIsEnumerable() { [native code] }
toLocaleString: function toLocaleString() { [native code] }
toString: function toString() { [native code] }
valueOf: function valueOf() { [native code] }
However, one can call Object.create() while supplying null as an argument:
myobj2 = Object.create(null);
In this case empty prototype will be returned:
Object
No Properties
And here goes the question: in which cases and why should I care to break the prototype chain to the original Object? Where it can be useful?
Update: as already corrected down below, I mean Object.create(Object.prototype) rather than Object.create(Object) that would return Function object (indeed Object() is a constructor function for Object prototypees).
Instead of this:
…I think you mean this is the equivalent:
…because:
As to why to use
nullearly, if your object has no need for any of the properties ofObject.prototype, ending the chain early would technically (though marginally) speed up property lookups when a property does not exist on the object in question.Note that I say “early” because the chain always ends with
null.Notice that the
bazproperty does not exist anywhere in the prototype chain.Because of this, it needs to search each object in sequence until it finally reaches
nullbefore it realizes thatbazdoesn’t exist anywhere.If you eliminate the
Object.prototypefrom the chain, it will get tonulla little quicker.