具有setTimeout闭包,变量访问的自调用函数

时间:2010-10-29 02:28:15

标签: javascript

如何从a_var开始访问setTimeout中的someFunction

感谢。

function someFunction(){
             (function why(){
                       setTimeout(function(){

                          var a_var='help I wanna get out!';
                         return a_var;//<-useless?

                      }, 25);
                   })();
        };

1 个答案:

答案 0 :(得分:1)

您必须在更高的范围内声明a_var,如下所示:

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