[Javascript] Advanced Function Scope

时间:2023-03-09 03:34:43
[Javascript] Advanced Function Scope

Something like 'for' or 'while', 'if', they don't create a new scope:

var ary = [,,];

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

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

So, the problem:

var ary = [,,];

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

Solve the problem:

var ary = [,,];

for(var i = ; 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]);
}, )
})();
}