Javascript异步执行时要小心的变量作用域

 1 function asyncFunction(callback){
 2     setTimeout(function(){
 3         callback()
 4     },200);
 5 }
 6 
 7 var color = 'blue';
 8 //调用上面的函数
 9 asyncFunction(function(){
10     console.log('the color is'+color);                             //green
11 });
12 //闭包函数
13 //To "freeze" the contents of the color variable you can modify your logic and use a JavaScript closure.
14 (function(color){
15     asyncFunction(function(){
16         console.log('the color is'+color);                        //blue
17     });
18     
19 })(color);
20 
21 color = 'green';

1.By making "color" an argument for anonymous function, it becomes local to the scope of that function and

when the value of color is changed outside of the anonymous function,the local version is unaffected.

原文地址:https://www.cnblogs.com/yuyutianxia/p/3258395.html