views:

38

answers:

2

In the following example, how do I modify the variable "sizeMod", which is a property of each object?

// 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?
        }
    };
});
+1  A: 

the second statement is destroying your original object where sizeMod is declared.

this should work (untested)

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

you may call as

objs['relevantkey'].change();
lincolnk
Elegant solution. Thanks.
Matrym
Does "this" always refer to the top object, or does it ever refer to a nested value (in terms of json objects with multiple levels).
Matrym
+1  A: 

see if this helps:

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