在Javascript中,如何遍历从给定构造函数继承的对象
In Javascript, how do I loop through objects inherited from a given constructor?
在下面的例子中,我如何循环遍历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];
}
}
相关文章:
- 如何检查DOM节点是否继承自构造函数
- Javascript:继承原型而不重新定义构造函数
- 从类构造函数继承javascript
- JavaScript-构造函数参数和原型继承
- Javascript继承构造函数
- JavaScript继承构造函数.prototype
- 通过父构造函数创建主干继承视图
- JavaScript - 构造函数中的继承
- 构造函数原型-继承混淆
- Crockford 伪经典继承部分中的函数构造函数
- 通过构造函数属性和运算符实例设置继承
- 如何从“构造函数返回另一个对象”对象继承
- 从原型继承与从构造函数继承
- 继承和 TypeScript 错误:X 不是构造函数类型
- 命名空间和继承:具有JavaScript责任链的超级构造函数
- 从另一个构造函数继承会覆盖继承的构造函数的原型链中的现有属性
- 在Javascript中,如何遍历从给定构造函数继承的对象
- 测试主干扩展构造函数继承的好方法是什么?
- 一个构造函数的属性是否可能被另一个构造函数继承?
- javascript构造函数.继承另一个构造函数的原型