2010-09-18 11 views
0

Dans l'exemple suivant, comment modifier la variable "sizeMod", qui est une propriété de chaque objet?Javascript - propriété d'un objet dans une autre propriété?

// Will be created by ids 
var objs = {}; 

// Set up objects 
$.each(ids, function(index, value){ 
    objs[value] = { 
     sizeMod: 0 
    }; 
    objs[value] = { 
     change: function(){ 
      sizeMod += 1; // How do I write this line correctly? 
     } 
    }; 
}); 

Répondre

1

la deuxième déclaration est en train de détruire votre objet original où sizeMod est déclarée.

cela devrait fonctionner (non testé)

$.each(ids, function(index, value){ 
    objs[value] = { 
     sizeMod: 0, 
     change: function(){ 
      this.sizeMod += 1; // How do I write this line correctly? 
     } 
    }; 
}); 

vous pouvez appeler comme

objs['relevantkey'].change(); 
+0

solution élégante. Merci. – Matrym

+0

Est-ce que "this" fait toujours référence à l'objet supérieur, ou fait-il référence à une valeur imbriquée (en termes d'objets json avec plusieurs niveaux). – Matrym

1

voir si cela aide:

. 
. 
. 
objs[value] = { 
    sizeMod: 0 
}; 
objs[value].change = function(){ 
    this.sizeMod += 1; 
} 
. 
. 
.