Looping through all instances of a javascript object

后端 未结 5 2000
清酒与你
清酒与你 2020-12-10 07:01

if I have an object constructor like:

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

and I make some cats:

相关标签:
5条回答
  • 2020-12-10 07:49

    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).

    0 讨论(0)
  • 2020-12-10 07:54

    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]);
        }
      } 
    };
    
    0 讨论(0)
  • 2020-12-10 07:58

    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);
    });
    
    0 讨论(0)
  • 2020-12-10 08:01

    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

    0 讨论(0)
  • 2020-12-10 08:08

    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.

    0 讨论(0)
提交回复
热议问题