You do not know the JS series (15) - cycling and closures

To illustrate closures, for common example is a loop
for (var i=1; i<=5; i++) {
  setTimeout(function timer() {
    console.log(i);
  }, 0)
}

Delayed callback function will be executed until the end of the cycle, when the execution of the loop, the variable's value has become a 6, so each time the output will be a 6. We believe that each iteration of the loop at run-time capture will give yourself a copy of i. But according to the principle scope, calls are the same i. It has only one i. If the delay function is defined callback was repeated five times, without using cycle, the same code is equivalent to

var i = 1;
setTimeout(function timer() {
  console.log(i);
}, 0)
i = 2;
setTimeout(function timer() {
  console.log(i);
}, 0)
i = 3;
setTimeout(function timer() {
  console.log(i);
}, 0)
i = 4;
setTimeout(function timer() {
  console.log(i);
}, 0)
i = 5;
setTimeout(function timer() {
  console.log(i);
}, 0)
i = 6;

6 output five times. We need more scope closures retain a reference to each of i



for (var i=1; i<=5; i++) {
  (function(){
    setTimeout(function timer() {
      console.log(i);
    }, 0)
  })()
}

This adds a layer of scope, but the scope it was empty, it needs its own variable, used to store the value of i

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

The line, it can normal work. We can make some improvements to this code:

 

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

Each iteration produces a new scope is so delayed callback functions are in possession of access to the internal variables. In other words, we all need each iteration a block scope, let it can be used to hijack block scope. Is essentially converted into a block scope scope can be closed

 

for (let i=1; i<=5; i++) {
  let j = i;
  setTimeout(function timer() {
    console.log(j);
  }, 0)
}

Such closed with multi-layer scope effect is the same. But the head of the loop for let statement will have a special behavior, this behavior so that the variable is declared more than sequentially in a loop, each iteration statement.

 

for (let i=1; i<=5; i++) {
  setTimeout(function timer() {
    console.log(i);
  }, 0)
}
Cool, block scope and closure together can invincible
 

 

Guess you like

Origin www.cnblogs.com/wzndkj/p/12364998.html