开发者

self invoking function with setTimeout closure, variable access

开发者 https://www.devze.com 2023-01-22 17:28 出处:网络
How would I get access to thea_var that is in setTimeout, from the outter someFunction? Thanks. function someFunction(){

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

精彩评论

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