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

时间:2022-09-06 18:18:04
 function asyncFunction(callback){
setTimeout(function(){
callback()
},200);
} var color = 'blue';
//调用上面的函数
asyncFunction(function(){
console.log('the color is'+color); //green
});
//闭包函数
//To "freeze" the contents of the color variable you can modify your logic and use a JavaScript closure.
(function(color){
asyncFunction(function(){
console.log('the color is'+color); //blue
}); })(color); 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.