[Javascript] Advanced Function Scope

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

 

posted @ 2016-04-25 16:23  Zhentiw  阅读(159)  评论(0编辑  收藏  举报