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

[Javascript] Advanced Function Scope

2016-04-25 16:23 731 查看
Something like 'for' or 'while', 'if', they don't create a new scope:

var ary = [1,2,3];

for(var i = 0; i < ary.length; i++){
var greeting = "Hello";
var times = i;
}

console.log(i); // 3
console.log(times); // 2
console.log(greeting); // Hello


Everyting written in for loop can be accessed outside the for loop.

So, the problem:

var ary = [1,2,3];

for(var i = 0; i < ary.length; i++){
setTimeout( function(i){
console.log(ary[i]); //undefined, becaues i = 3 always
}, 0)
}


Solve the problem:

var ary = [1,2,3];

for(var i = 0; i < ary.length; i++){
// Function do create scope
(function(){
// Remember i in j
var j = i;
setTimeout( function(){
// So now each j is different
console.log(ary[j]);
}, 0)
})();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: