Reputation: 8685
I am trying to update a value from within the object itself. I have the following code:
var stepData = {
0: {
ref: "Home",
values: {
},
init: function(){
stepData[1].ref = 'new value';
alert(stepData[1].ref);
return;
},
save: function(){
}
},
1: {
ref: "one"
}
}
$("#run").click(function(){
stepData[0].init();
});
Which works fine. However, I can't replace
stepData[1].ref = 'new value';
alert(stepData[1].ref);
with
this[1].ref = 'new value';
alert(this[1].ref);
Why not?
EDIT: sorry, mistake in original code. Fixed now.
Upvotes: 1
Views: 37
Reputation: 101690
It doesn't work because if you call stepData[0].init()
, then this
refers to stepData[0]
, not stepData
.
One way to improve the situation is to use an immediately invoked function to create your object:
var stepData = (function(){
var mySelf = {
0: {
ref: "Home",
values: {
},
init: function(){
mySelf[1].ref = 'new value';
alert(mySelf[1].ref);
return;
},
save: function(){
}
},
1: {
ref: "one"
}
};
return mySelf;
})();
The following will break the code that you have now:
var newVariable = stepData;
stepData = null;
newVariable[0].init();
but it will not break the approach above.
Upvotes: 0
Reputation: 1074385
this
is set primarily by how a function is called, not where it's defined. Your code:
$("#run").click(function(){
stepData[0].init();
});
...calls init
with this
set to stepData[0]
.
You can call it with this
set to stepData
if you like, using Function#call
:
$("#run").click(function(){
stepData[0].init.call(stepData);
});
From your comment on the question:
So the way I've got it is OK then?
Yes, as long as stepData
is a singleton, there's no particular need to use this
in its functions.
More about this
(on my blog):
Upvotes: 1