闭包与ES6 Let [英] Closures versus ES6 Let
问题描述
尝试使用闭包和let来在for循环中打印一系列数字:
Trying to print series of numbers inside for loop using closures and with let:
请考虑以下示例:
for(var i=1; i<10; i++){
setTimeout(function(){
document.write(i);
}, 1000);
}
输出为:
101010101010101010
101010101010101010
关闭时:
for(var i=1; i<10; i++){
(function(x){
setTimeout(function(){
document.write(x);
}, 1000);
})(i);
}
输出为:
123456789
123456789
不关闭,仅使用ES6 let:
Without closure, just using ES6 let:
for(let i=1; i<10; i++){
setTimeout(function(){
document.write(i);
}, 1000);
}
输出为:
123456789
123456789
试图了解我们是否仍需要使用向ES6过渡的IIFE块进行封闭?
Trying to understand if we still need closures using IIFE blocks moving towards ES6?
如果我们真的需要用ES6闭包,有什么好例子?
Any good example if we really need closures with ES6?
推荐答案
以下是Kleo Petrov的一个很好的解释-
Here's a good explanation by Kleo Petrov -
IIFE是ES5中最常用的模式之一,因为函数是声明作用域代码块的唯一方法.在ES6中,我们可以使用模块来代替IIFE:
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();
您可能想在ES6中使用IIFE的唯一情况是带有立即调用的箭头函数,该函数需要多个表达式,例如:
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('');
})();
这篇关于闭包与ES6 Let的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!