I've been testing JavaScript's Object.prototype.hasOwnProperty
. From my understanding, it is designed to weed out direct object properties from inherited object properties.
However, in the contrived examples I've tested so far (including MDN's own's example), I have been unsuccessful at console-logging inherited properties (i.e. toString
) when .hasOwnProperty()
returns false
, which makes me a bit skeptical on its functionality. So,
1) Could you provide example code which I can run in the console, that will log inherited properties when hasOwnProperty()
returns false
?
2) When adding the hasOwnProperty tag to this question, the SO description that popped up states "...does not traverse through the prototype chain". If that's the case, what is the point of Mozilla's example below, since the "else clause will never be executed?
Here's Mozilla's example code:
var buz = { fog: 'stack' };
for (var name in buz) { if (buz.hasOwnProperty(name)) {
console.log('this is fog (' + name + ') for sure. Value: ' + buz[name]);
} else {
console.log(name); // toString or something else
}
}
for...in
only iterates over enumerable properties. All the properties on Object.prototype
are not enumerable, so they won't actually be iterated over.
Here is an example that would show inherited properties. We create a new object that inherits from another object, not from Object.prototype
:
var foo = {abc: 123};
// Creates an object with property `fog: 'stack'` but has `foo` as its prototype
var buz = Object.create(foo, {fog: {value: 'stack', enumerable: true}});
for (var name in buz) {
if (Object.prototype.hasOwnProperty.call(buz, name)) {
console.log('this is fog (' + name + ') for sure. Value: ' + buz[name]);
} else {
console.log(name); // toString or something else
}
}
(of course we could also assign to Object.prototype
, but we are trying to be good citizens :) )