闭包基本上是内部函数能够访问其范围以外的变量,可用于实现隐私和建立函数工厂数组
先看一个不正确的写法:闭包
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。this
缘由:由于setTimeout
函数建立的是一个能够访问其外部做用域的函数(闭包),该做用域包含索引i
的循环。通过3
秒后,i
的值已经变为4
。spa
正确的写法:写法一:
code
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); }