在类似下面的示例中,我将如何循环遍历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 }
}
*/
答案 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];
}
}