if I have an object constructor like:
function cat(color, sex){
this.color = color;
this.sex = sex;
}
and I make some cats:
How about this:
var Cat = (function cat(color, sex) {
var allCats = [],
catConstructor = function () {
allCats.push(this);
this.color = color;
this.sex = sex;
};
catConstructor.each = function (fn) {
for (var i = 0; i < allCats.length; i++) {
fn.call(allCats[i]);
}
};
return catConstructor;
}()); // execute the function immediately
With this one, you don't have any nasty global vars, and you don't have to alter your interface from the Cat
prototype form.
var fluffy = new Cat('brown', 'male'),
kitty = new Cat('black', 'female');
Cat.each(function () {
alert(this.color);
});
You can make your loop interface whatever you want (a getAllCats()
function which returns an array, or whatever).
You could make a sort of a CatFactory object, dedicated to create and track the Cat object instances:
Usage:
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);
});
Implementation:
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]);
}
}
};
since i just had a similar problem, here's one easy solution if you use jquery
:
function Cat(color, sex){
this.color = color;
this.sex = sex;
}
var cats = [];
function createCat(color, sex)
{
cats.push(new Cat(color, sex)));
}
createCat("white", "male");
createCat("black", "female");
//iterating cats by using jQuery's $.each
$.each(cats, function(index, object){
alert(object.color);
});
It is not possible to loop through all the objects you have created unless you kept track of them somewhere (like in the constructor). Something like this-
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
Watch out though. As long as the objects are in the array, they stay in memory without garbage collected. So if you create a lot of objects, you may want to remove them from the array once you are done with it.
Also, do not use for..in
to iterate though loops. See this Javascript Array extension
If you want to go through all of them storing them in array would make sense..
Something along the lines of var cats = [];
cats[0] = new cat();
cats[0].color = "red";
cats[0].name = "fluffy";
for ( var cur in cats )
{
//Do Things
}
Sorry for all the edits- half asleep tonight.