Basically everyone writing about member enumeration in JavaScript heavily advocates the use of the hasOwnProperty method as to avoid going up the prototype-chain.
I understand that this is a form of defensive programming as to prevent iterating over members that are added, for example, to the Object.prototype. But what about the other inherited members? Say, members that are very close in the prototype chain...members that you actually Want to be enumerated over.
Let's say I have the following:
var beget = function (o) { // http://javascript.crockford.com/prototypal.html
function F() {};
F.prototype = o;
return new F();
};
var john = { name: 'john', surname: 'grech' },
mary = beget(john),
p;
mary.age = 42; //augmenting 'mary'
// 'surname' in mary => true
// mary.hasOwnProperty('surname') => false
for (p in mary) {
//skipping over non-direct members, meaning that we also skip members
//inherited from 'john'
if (!mary.hasOwnProperty(p)) {
continue;
}
console.log(p);
}
In the above sample, only age will be displayed, since age is the only direct-member of mary...the other two members, name and surname, are up the prototype chain.
But obviously, I want all the 3 members to be iterated over in the for..in construct; but if you remove the hasOwnProperty, you can then get members from Object.Prototype if someone adds functions to it.
So this is my dilemma.
Do you use prototypal inheritance in combination with the hasOwnProperty method but risk getting members that are too far up the chain during enumeration?
Or do you use the other forms of inheritance that add members directly to the object rather than the prototype?