I see a lot of people doing this
Object.prototype.foo = 'HALLO';
var hash = {baz: 'quuz'};
for ( var v in hash ) {
// Do not print property `foo`
if ( hash.hasOwnProperty(v) ) {
console.log( v + " is a hash property" );
}
}
My question is rather than testing .hasOwnProperty
each time you wish to use an Object
as a hash why not just set the .__proto__
to null
on the object? †
hash.prototype = null;
hash.__proto__ = null;
for ( var v in hash ) {
// Do not print property `foo`
console.log( v + " is a hash property" );
}
It has been brought to my attention that __proto__
is nonstandard. That still doesn't answer the question though...
var foo = Object.create(null); Object.getPrototypeOf(foo);
This can't be an original question, but I can't find anything about changing __proto__
to null
to eliminate the drawbacks of having to check for inheritance? What's wrong with this approach, seems to make code faster (don't have to check properties of Object
) and cleaner?
† And the .prototype
property if you plan on making future children of it.