2009-08-08 9 views
5

si tengo un constructor de objetos como:bucle a través de todas las instancias de un objeto JavaScript

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

y hacer algunos gatos:

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

¿Es posible recorrer todos los gatos que tengo ¿declarado? Algo así como:

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

Eso no funciona. ¿La gente suele almacenar todos los objetos de gato en una matriz? O hacer otro objeto que contiene una matriz de los gatos individuales:

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

Gracias por cualquier consejo!

Respuesta

0

Si quieres ir a través de todos ellos almacenándolos en conjunto tendría sentido ..

Algo a lo largo de las líneas de gatos var = [];

cats[0] = new cat(); 

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

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

Lo siento por todas las ediciones, medio dormido esta noche.

5

No es posible recorrer todos los objetos que ha creado a menos que los haya rastreado en algún lugar (como en el constructor). Algo como esto:

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 

Ten cuidado. Siempre que los objetos estén en la matriz, permanecen en la memoria sin la basura recolectada. Por lo tanto, si crea muchos objetos, es posible que desee eliminarlos de la matriz una vez que haya terminado con ellos.

Además, no utilice for..in para iterar a través de bucles. Ver este Javascript Array extension

4

Se podría hacer una especie de objeto CatFactory, dedicada a crear y realizar un seguimiento de las instancias de objetos del gato:

Uso:

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

Implementación:

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

Absolutamente maravilloso!El único código que pude encontrar aglomera creando instancias Y control/guardar para manipulaciones futuras. Elegante y genio! –

1

Qué tal esto:

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 este, no tiene ningún vars global desagradable, y no tiene que modificar su interfaz del formulario de prototipo Cat.

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

Usted puede hacer su interfaz de bucle de lo que quieras (una función getAllCats() que devuelve una matriz, o lo que sea).

0

ya que sólo tenía un problema similar, aquí está una solución fácil si utiliza 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); 
}); 
Cuestiones relacionadas