search

Home  >  Q&A  >  body text

javascript - How to implement ES5 closures using ES6

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);
    })
}
三叔三叔2739 days ago939

reply all(6)I'll reply

  • 给我你的怀抱

    给我你的怀抱2017-06-30 10:01:41

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

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-06-30 10:01:41

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

    reply
    0
  • 学习ing

    学习ing2017-06-30 10:01:41

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

    reply
    0
  • 世界只因有你

    世界只因有你2017-06-30 10:01:41

    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

    reply
    0
  • 阿神

    阿神2017-06-30 10:01:41

    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

    reply
    0
  • PHP中文网

    PHP中文网2017-06-30 10:01:41

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

    reply
    0
  • Cancelreply