开发者

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!'; 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜