Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

javascript - Closures versus ES6 Let

Trying to print series of numbers inside for loop using closures and with let:

Consider the following example:

  for(var i=1; i<10; i++){      
      setTimeout(function(){
        document.write(i);
      }, 1000);
  }

Output is:

101010101010101010

With Closures:

  for(var i=1; i<10; i++){    
    (function(x){      
      setTimeout(function(){
        document.write(x);
      }, 1000);      
    })(i);
  }

Output is:

123456789

Without closure, just using ES6 let:

 for(let i=1; i<10; i++){      
      setTimeout(function(){
        document.write(i);
      }, 1000);
  }

Output is:

123456789

Trying to understand if we still need closures using IIFE blocks moving towards ES6?

Any good example if we really need closures with ES6?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's a good explanation by Kleo Petrov -

Do ES6 Modules make the case of IIFEs obsolete?

IIFE was one of the most used patterns in the ES5, as functions were the only way to declare a scoped block of code. In ES6, instead of using IIFE, we can use modules:

// myModule.js

let counter = 0;

export function increment() {
    counter++;
}    

// logic.js

import {increment} from 'myModule.js';

increment();

The only case, where you may want to use an IIFE in ES6, is with an immediately-invoked arrow functions, that requires more than a single expression, for example:

const SENTENCE = 'Hello world, how are you?';
const REVERSE = (() => {
    const array  = [...SENTENCE];
    array.reverse();
    return array.join('');
})();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...