如果我有一个对象构造函数,如:
function cat(color, sex){
this.color = color;
this.sex = sex;
}
Run Code Online (Sandbox Code Playgroud)
我做了一些猫:
var fluffball = new cat("blue","male");
var shiznitz = new cat("red","male");
var slothersburger = new cat("green","female");
Run Code Online (Sandbox Code Playgroud)
是否有可能遍历我宣布的所有猫?就像是:
var current_cat;
for(current_cat in document.cat){
alert(current_cat.color);
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用.人们通常将所有猫对象存储在一个数组中吗?或者制作另一个包含各个猫的数组的对象:
function all_cats(){
this.the_cats = new Array();
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的任何提示!
除非您在某处(例如在构造函数中)跟踪它们,否则无法遍历您创建的所有对象.像这样的东西 -
var globalCatArray = [];
function cat(color, sex){
this.color = color;
this.sex = sex;
globalCatArray.push(this);
}
var fluffball = new cat("blue","male");
var shiznitz = new cat("red","male");
var slothersburger = new cat("green","female");
//use globalCatArray to get all instances
Run Code Online (Sandbox Code Playgroud)
但请注意.只要对象在数组中,它们就会保留在内存中而不会收集垃圾.因此,如果您创建了大量对象,则可能需要在完成后从阵列中删除它们.
另外,不要使用for..in迭代循环.请参阅此Javascript数组扩展
您可以创建一个CatFactory对象,专门用于创建和跟踪Cat对象实例:
用法:
CatFactory.createCat('fluffball', 'blue','male');
CatFactory.createCat('shiznitz', 'red','male');
CatFactory.createCat('slothersburger', 'green','female');
CatFactory.forEachCat (function () { // forEach abstraction
alert(this.name + ' is ' + this.color);
});
Run Code Online (Sandbox Code Playgroud)
实现方式:
function Cat (name, color, sex){
this.name = name;
this.color = color;
this.sex = sex;
}
CatFactory = {
createCat: function () {
var newCat = {};
Cat.apply(newCat, arguments);
this.allCats.push(newCat);
return newCat;
},
allCats: [],
forEachCat: function (action) {
for (var i = 0; i < this.allCats.length; i++){
action.call(this.allCats[i]);
}
}
};
Run Code Online (Sandbox Code Playgroud)
如果你想遍历所有这些,将它们存储在数组中是有意义的。
类似于 var cats = []; 的东西
cats[0] = new cat();
cats[0].color = "red";
cats[0].name = "fluffy";
for ( var cur in cats )
{
//Do Things
}
Run Code Online (Sandbox Code Playgroud)
抱歉所有的编辑——今晚半睡半醒。
| 归档时间: |
|
| 查看次数: |
7658 次 |
| 最近记录: |