如何在数组循环中访问原型函数

时间:2018-06-06 19:40:05

标签: javascript arrays prototype

我有以下对象结构(只是一个示例对象):

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() );

当我做上面的事情时,效果很好并且必须在控制台内打印。但是当我有一个数组集合时,我无法访问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.lenght; i++ )
{ console.log ( biblio[i].getName() ); }

对于上述情况,我总是得到undefined。但在for之外使用类似biblio[0].getName()的内容,效果很好。

如何在for循环中访问对象的功能?

1 个答案:

答案 0 :(得分:3)

只需更正此biblio.length,它就可以根据您的需要进行操作!

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() ); }