闭包基本上是内部函数能够接见其局限以外的变量,可用于完成隐私和建立函数工场
定义一个数组,轮回遍历这个数组并在耽误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);
}