JavaScript 如何使用閉包

閉包基本上是內部函數能夠訪問其範圍以外的變量,可用於實現隱私和建立函數工廠數組

定義一個數組,循環遍歷這個數組並在延遲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);
}

看下執行效果函數

clipboard.png

如上圖:3秒後每次都是打印4,而不是0123this

緣由:由於setTimeout函數建立的是一個能夠訪問其外部做用域的函數(閉包),該做用域包含索引i的循環。通過3秒後,i的值已經變爲4spa

正確的寫法:
寫法一: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)
}

clipboard.png

寫法二:索引

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);
}

clipboard.png

相關文章
相關標籤/搜索