2009-08-08 20 views
5

se ho un costruttore di oggetto come:Looping attraverso tutte le istanze di un oggetto JavaScript

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

e faccio alcuni gatti:

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

è possibile scorrere tutti i gatti che ho dichiarato? Qualcosa di simile:

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

Questo però non funziona. Le persone solitamente memorizzano tutti gli oggetti cat in un array? Oppure crea un altro oggetto contenente un array dei singoli gatti:

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

Grazie per eventuali suggerimenti!

risposta

0

Se si vuole passare attraverso tutti loro la loro memorizzazione in serie avrebbe senso ..

Qualcosa sulla falsariga di gatti var = [];

cats[0] = new cat(); 

cats[0].color = "red"; 
cats[0].name = "fluffy"; 

for (var cur in cats) 
{ 
    //Do Things 
} 

Scusate per tutte le modifiche, mezza addormentata questa sera.

5

Non è possibile eseguire il ciclo di tutti gli oggetti creati a meno che non li abbia tenuti traccia da qualche parte (come nel costruttore). Qualcosa del genere-

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 

Attenzione però. Finché gli oggetti sono nell'array, rimangono in memoria senza garbage collection. Quindi, se crei molti oggetti, puoi rimuoverli dalla matrice una volta che hai finito.

Inoltre, non utilizzare for..in per ripetere i cicli. Vedere questo Javascript Array extension

4

Si potrebbe fare una sorta di un CatFactory oggetto, dedicata a creare e tenere traccia delle istanze di oggetti Cat:

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

Implementazione:

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

Assolutamente meraviglioso!L'unico pezzo di codice che ho trovato è che crea gli istanze E controlla/salva per manipolazioni future. Elegante e geniale! –

1

Che ne dite di questo:

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 

Con questo, non si hanno brutte vars globali e non è necessario modificare l'interfaccia dal modulo prototipo Cat.

var fluffy = new Cat('brown', 'male'), 
    kitty = new Cat('black', 'female'); 
Cat.each(function() { 
    alert(this.color); 
}); 

È possibile rendere l'interfaccia ciclo quello che vuoi (una funzione getAllCats() che restituisce un array, o qualsiasi altra cosa).

0

dato che ho appena avuto un problema simile, ecco una soluzione facile se si utilizza 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); 
}); 
Problemi correlati