caiquearaujo
caiquearaujo

Reputation: 417

How to access a prototype function in a array loop

I've the following object structure (just a sample object):

var Sample = function Sample (name)
{ this.init(name); };

Sample.prototype.init = function (name)
{ this.name_ = name; }

Sample.prototype.getName = function ()
{ return 'The name is '+this.name_; }

var obj = new Sample();
console.log ( obj.getName() );

When I do something like above it works well and print inside console as it has to be. But when I have a array collection I can't access the getName() function. For exemple:

var biblio = [];

biblio.push(new Sample('A'));
biblio.push(new Sample('B'));
biblio.push(new Sample('C'));
biblio.push(new Sample('D'));

for ( var i = 0; i < biblio.lenght; i++ )
{ console.log ( biblio[i].getName() ); }

For the case above, I always get undefined. But outside of the for usign something like biblio[0].getName() it works well.

How can I access the function of a object in a for loop?

Upvotes: 0

Views: 50

Answers (1)

Nishant Dixit
Nishant Dixit

Reputation: 5522

Just correct this biblio.length and It will work according to you!.

var Sample = function Sample (name)
{ this.init(name); };

Sample.prototype.init = function (name)
{ this.name_ = name; }

Sample.prototype.getName = function ()
{ return 'The name is '+this.name_; }

var obj = new Sample();
console.log ( obj.getName() );

var biblio = [];

biblio.push(new Sample('A'));
biblio.push(new Sample('B'));
biblio.push(new Sample('C'));
biblio.push(new Sample('D'));

for ( var i = 0; i < biblio.length; i++ )
{ console.log ( biblio[i].getName() ); }

Upvotes: 3

Related Questions