I have a simple Javascript method (member function of an object) which keeps an internal cache (to avoid unnecessary ajax requests.)
I must be confused about Javascript scope rules or something because updates to the cache don't seem to be visible if they're made from within a nested function.
For example:
window.mynamespace = window.mynamespace || { };
window.mynamespace.foo = function()
{
this.cache = this.cache || { };
alert(JSON.stringify(this.cache));
this.cache["foo"] = "bar";
}
Here's a simple example that is meant to demonstrate that items inserted into the cache are being remembered across calls to mynamespace.foo().
In my onload or $(document).ready() handler, if I say:
window.mynamespace.foo();
window.mynamespace.foo();
I get two alerts, where the first shows me {} and the second shows me {"foo" : "bar"}. Okay great, that's exactly what I expected. So my cache seems to work.
But... if I try to update the cache from within a nested function (specifically within a callback handler of some async operation), the updates to my cache don't seem to propagate.
For example:
window.mynamespace = window.mynamespace || { };
window.mynamespace.foo = function()
{
var instance = this;
this.cache = this.cache || { };
alert(JSON.stringify(this.cache));
window.setTimeout(
function()
{
instance.cache["foo"] = "bar";
},
0
);
}
Here, I update the cache from within a nested function (a callback handler for window.setTimeout).
In this case, if I call window.mynamespace.foo() twice from within my document onload handler, I get two alerts, each showing me {} - an empty object. So now my cache is not updating.
Okay, so something about my understanding of Javascript scoping rules here is broken. I realize that this means something different from within a nested function, which is why I specifically use the instance variable which always refers to the window.mynamespace.foo object.
Please educate me about my error here.
setTimeoutcode runs in the future. So of course the second alert shows an empty object, because the cache has not been modified yet.