JavaScript 如何使用闭包

26次阅读

共计 711 个字符,预计需要花费 2 分钟才能阅读完成。

闭包基本上是内部函数可以访问其范围之外的变量,可用于实现隐私和创建函数工厂
定义一个数组,循环遍历这个数组并在延迟 3 秒后打印每个元素的索引
先看一个不正确的写法:
const arr = [10, 12, 15, 21];
for (var i = 0; i < arr.length; i++) {
setTimeout(function() {
alert(‘The index of this number is: ‘ + i);
console.log(‘The index of this number is: ‘ + i);
}, 3000);
}

看下执行效果:

如上图:3 秒后每次都是打印 4,而不是 0,1,2,3。
原因:因为 setTimeout 函数创建的是一个可以访问其外部作用域的函数(闭包),该作用域包含索引 i 的循环。经过 3 秒后,i 的值已经变为 4。
正确的写法:写法一:
const arr = [10, 12, 15, 21];
for (var i = 0; i < arr.length; i++) {
setTimeout(function(i_local){
return function () {
alert(‘The index of this number is: ‘ + i_local);
console.log(‘The index of this number is: ‘ + i_local);
}
}(i), 3000)
}

写法二:
const arr = [10, 12, 15, 21];
for (let i = 0; i < arr.length; i++) {
setTimeout(function() {
alert(‘The index of this number is: ‘ + i);
console.log(‘The index of this number is: ‘ + i);
}, 3000);
}

正文完
 0