self invoking function with setTimeout closure, variable access
How would I get access to the a_var
that is in setTimeout
, from the outter someFunction
?
Thanks.
function someFunction(){
开发者_StackOverflow社区 (function why(){
setTimeout(function(){
var a_var='help I wanna get out!';
return a_var;//<-useless?
}, 25);
})();
};
You have to declare a_var in a higher scope, like so:
var a_var = 'I can help from here';
function someFunction(){
setTimeout(function(){
a_var = "help I wanna get out!";
}, 25);
}
someFunction();
console.log(a_var); // logs 'I can help from here'
setTimeout(function(){
console.log(a_var);
}, 30); // logs 'help I wanna get out!';
精彩评论