在Javascript中,如何循环从给定构造函数继承的对象?

时间:2011-11-27 18:14:46

标签: javascript inheritance

在类似下面的示例中,我将如何循环遍历apple原型中的每个对象?

function apple(id,name,color) {
    this.id = id;
    this.name = name;
    this.color = color;
}


apple1 = new apple(0,"Golden Delicious","Yellow");
myapple = new apple(1,"Mcintosh","Mixed");
anotherapple = new apple(2,"Bramley","Green");



/*
for each instance of apple {

  if (this one is "Green") { do something }

}
*/

2 个答案:

答案 0 :(得分:2)

我使用类似静态属性的东西,其中包含对所有实例的引用。您将在构造函数中添加每个实例:

function apple(id,name,color) {
    this.id = id;
    this.name = name;
    this.color = color;
    apple.instances.push(this);
}
apple.instances = [];

然后,您可以遍历apple.instances

答案 1 :(得分:1)

我使用大写名称作为构造函数,因此语法高亮显示器得到它:

function Apple(name,color) {
    this.name = name;
    this.color = color;
    this.id = this.constructor.getId();
    this.constructor.instances[this.id] = this;
}

Apple.instances = {};

Apple.getId = (function(){
var i = 0;

    return function(){
    return i++;
    };

})();

/* ... */


var instance, key;

for( key in Apple.instances ) {
instance = Apple.instances[key];

    if( instance.color == "green" ) {
     delete Apple.instances[instance.id];

    }
}