閉包基本上是內部函數能夠訪問其範圍以外的變量,可用於實現隱私和建立函數工廠數組
先看一個不正確的寫法:閉包
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); }