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

相关文章
相关标签/搜索