在Javascript中,如何遍历从给定构造函数继承的对象

In Javascript, how do I loop through objects inherited from a given constructor?

本文关键字:构造函数 继承 对象 遍历 Javascript 何遍历      更新时间:2023-09-26

在下面的例子中,我如何循环遍历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 }
}
*/

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

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

然后,可以遍历apple.instances

我使用大写的构造函数名称,以便语法高亮显示它:

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];
    }
}