javascript - How to implement ES5 closures using ES6
三叔
三叔 2017-06-30 09:59:41
0
6
937

How to implement the following code using es6 let,

for(var i = 0; i < 3;i++) {
    (function(j){
        $.ajax({
            url: 'xxx',
            success: function(){
                console.log(j);
            }
        })(i);
    })
}
三叔
三叔

reply all(6)
给我你的怀抱
for(let i = 0; i < 3;i++) {
        $.ajax({
            url: 'xxx',
            success: function(){
                console.log(i);
            };
        });
}
我想大声告诉你

What the questioner wants to ask is, how to solve i in ES6? Is it not a problem of the current i`?

In

ES5 it is solved using closures, in ES6 you can use let

for(let i = 0; i < 3;i++) {
    $.ajax({
        url: 'xxx',
        success: function(){
            console.log(i);
        }
    });
}
学习ing

This is the same with ES6, closures are still closures.

世界只因有你

Replace var with let

for(let i = 0; i < 3;i++) {
    $.ajax({
        url: 'xxx',
        success: function(){
            console.log(j);
        }
    })
}

The test is as follows (use setTimeout to simulate asynchronous requests):

for(var i = 0; i < 3;i++) {
  setTimeout(function(){
    console.log(i)
  }, 123)
}

Print 3 3

ES5 is solved with closure

for(var i = 0; i < 3;i++) {
  (function(i) {
    setTimeout(function(){
      console.log(i)
    }, 123)
  })(i)
}

es6 is easy with let

for(let i = 0; i < 3;i++) {
  setTimeout(function(){
    console.log(i)
  }, 123)
}

let allows you to declare a variable, statement or expression whose scope is restricted to the block level

阿神

I also found the answer, ES6 can directly remove closures

for(let i = 0; i < 3;i++) {
    $.ajax({
        url: 'xxx',
        success: function(){
            console.log(i);
        }
    });
}

The result is the same as using closure, thank you everyone

Ty80

There is absolutely no need in ES6, just let it be done
http://www.softwhy.com/articl...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template