Loops and closures

for (var i=1; i<=5; i++) {
  setTimeout( function delay(){
     console.log( i );
  }, i*100);
}

輸出是?

The i variable is being updated after the function is bound. This means that every bound function handler will always print the last value stored in i. In fact, the timeout function callbacks are running after the completion of the loop.

for (var i=1; i<=5; i++) {
   (function(j){
       setTimeout( function delay(){
          console.log( j );
       }, j*100);
   })( i );
}

We pass the i variable and copy it to the j variable local to the IIFE. The introduction of an IIFE inside each iteration creates a new scope for each iteration and hence updates the local copy with the correct value.
閉包在js裏面是用來頻繁使用用來封裝一些private information.

function privateTest(){
      var points=0;
      this.getPoints=function(){
         return points;
      };
     this.score=function(){
        points++;
     };
}
var private = new privateTest();
private.score();
console.log(private.points); // undefined
console.log(private.getPoints());
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章