I looked at this: Returning values from nested functions in Javascript
but it did not really help me (or I am just too dumb to get it).
My variable scope is somehow off and I don't understand why. My alert() does not behave as expected. Tried to add comments on all lines to explain what I'm thinking.
Thanks very much for any comments/pointers/answers!
var g = {}; / is a large object with all kinds of other stuff and functions in it
g.ding = function(){ // my problem function
var baby = 'young'; // i thought I set a local var here
if(someVar==true) { // standard issue if statement
someAPI.class( // using an API that uses a function as its attribute
function(stuff){ // my anonymous function
baby = 'old'; // setting the var to something
}
);
}
return baby; // returning the var
}
alert( g.ding() ); // i expect it to say "old" but it keeps saying "young". why?
NEW EDIT: Juan's accepted answer is great, but isn't there also a way to use setTimeout() to deal with asynchronous function calls and essentially making them synchronous? if anyone who reads this knows the answer I'd love to know. Thanks.