[Javascript] Advanced Function Scope

2023-04-25,,

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]);
}, )
})();
}

[Javascript] Advanced Function Scope的相关教程结束。

《[Javascript] Advanced Function Scope.doc》

下载本文的Word格式文档,以方便收藏与打印。