Matrym
Matrym

Reputation: 17053

Javascript - property of an object in another property?

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

Upvotes: 0

Views: 164

Answers (2)

Salman Arshad
Salman Arshad

Reputation: 272096

see if this helps:

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

Upvotes: 1

lincolnk
lincolnk

Reputation: 11238

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

Upvotes: 1

Related Questions