Are global variables accessible in jquery nested functions?
Im having an issue that i cant solve. One object property changes and another one doesn’t
The situtation is this
for(var key in object) {
if(object[key].boolean) {
alert(object[key].value)
$.get(url, "data", function(data) {
if(parseInt(data) > object[key].int) {
alert(object[key].value);
object.int = data;
}
});
}
}
The issue i am having is the object[key].value does not hold its value. Both alerts have different values so i cant use it in the nested return function. Also object[key].int gets updated correctly which is more confusing. Object is declared as a global variable.
Any suggestions is greatly appreciated.
your anonymous wrapper is called only after get becomes success,it is not called right away, looks like some situation like
Return a function from the anonymous wrapper?
are you getting the last item alerted from the inside closure?
Fiddle : http://jsfiddle.net/eTdv5/1/ (check console logs)
Explaining the whole thing is not becessary as I guess, you can check the above mentioned SO post, In case of anything unclear please ask.
Explanation:
First,
key = 10(function(key) {})(key)is like callingdisplay(key), think that you are writing display function right away and calling it with an argumentkey.return function(data) {};will return a function, in effect think like(function(key) {})(key)getting replaced with this returned function.That will give you an introduction, now how the scope is managed:
The
keywill change its value as thefor inloop loops throughobject, but each callback function we created has its ownkeyAliasassosiated with it which corresponds to the value ofkeyat the time callback function was crated using(function(key) {})(key)