I have some code:
var obj = function() { }; // functional object
obj.foo = 'foo';
obj.prototype.bar = 'bar';
for (var prop in obj) {
console.log(prop);
}
What surprised me is that all that is logged is foo
. I expected the for loop to iterate over the properties of the obj
's prototype as well (namely bar
), because I did not check for hasOwnProperty
. What am I missing here? And is there an idiomatic way to iterate over all the properties in the prototype as well?
I tested this in Chrome and IE10.
Thanks in advance.
If you want to maintain an inheritance hierarchy by defining all the properties even before the object instantiation, you could follow the below approach. This approach prints the prototype hierarchy chain.
Note: In this approach you don't have to create the constructor initially.
You're iterating over the constructor's properties, you have to create an instance. The instance is what inherits from the constructor's
prototype
property: