Closure compared to ES6.

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

Consider the following example:

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

Output:

10101010101010101010

With closing:

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

Output:

123456789

Without closing, just using ES6 let:

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

Output:

123456789

Trying to figure out if locks are still needed using IIFE blocks moving to ES6?

Any good example if we really need ES6 closures?

+6
source share
4 answers

Here is a good explanation of Cleo Petrov -

Can ES6 Modules Deprecate IIFE Cases?

IIFE was one of the most commonly used templates in ES5, because functions were the only way to declare code scope. 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();

, , , IIFE ES6, - , , :

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

let , . .

let, . IIFE , .

+5

, , :

function makeCounter() {
  let currentCount = 1;

  return function() { 
    return currentCount++;
  };
}

let counter = makeCounter(); 


console.log( counter() ); // 1
console.log( counter() ); // 2
console.log( counter() ); // 3
+3

, , , Es6.

N. Zachas, github ( , , , , ).

, , , , , for(var i = 0; i < length; i++){} .

Keep in mind, however, that you probably want to upgrade your code to es5 using either Babel or Tracer. In this case, the way these tools are used to simulate block coverage is to use closures. Thus, you probably should understand the pattern anyway for the purpose of completion and debugging.

Example transpilation from an example in a book here

+1
source

Source: https://habr.com/ru/post/1667977/


All Articles