您的位置:首页 > Web前端 > JavaScript

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

2013-08-14 20:08 393 查看
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: