Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over an object's prototype's properties

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.

like image 235
jds Avatar asked Sep 24 '13 17:09

jds


People also ask

Which iterator do we use to iterate over the properties of objects?

If you would like to iterate directly over the values of the keys of an object, you can define an iterator , just like JavaScipts's default iterators for strings, arrays, typed arrays, Map and Set. JS will attempt to iterate via the default iterator property, which must be defined as Symbol. iterator .

How do I iterate over an object key?

You have to pass the object you want to iterate, and the JavaScript Object. keys() method will return an array comprising all keys or property names. Then, you can iterate through that array and fetch the value of each property utilizing an array looping method such as the JavaScript forEach() loop.


1 Answers

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:

var Ctor = function() { }; // constructor function
Ctor.prototype.bar = 'bar';
var obj = new Ctor(); // instantiation

// adds own property to instance
obj.foo = 'foo';

// logs foo and bar
for (var prop in obj) {
    console.log(prop); 
}
like image 134
bfavaretto Avatar answered Oct 26 '22 16:10

bfavaretto