views:

206

answers:

3

Hi, if I have an object constructor like:

function cat(color, sex){
     this.color = color;
     this.sex = sex;
}

and I make some cats:

var fluffball = new cat("blue","male");
var shiznitz = new cat("red","male");
var slothersburger = new cat("green","female");

Is it possible to loop through all the cats I have declared? Something like:

var current_cat;
for(current_cat in document.cat){
     alert(current_cat.color);
}

That doesn't work though. Do people usually store all the cat objects in an array? Or make another object containing an array of the individual cats:

function all_cats(){
     this.the_cats = new Array();
}

Thanks for any tips!

A: 

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.

apocalypse9
+1  A: 

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 http://stackoverflow.com/questions/1234449/javascript-array-extension/1234482

Chetan Sastry
+1  A: 

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