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

看下实行结果

《JavaScript 怎样运用闭包》

如上图:3秒后每次都是打印4,而不是0123

缘由:由于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)
}

《JavaScript 怎样运用闭包》

写法二:

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

《JavaScript 怎样运用闭包》

    原文作者:终极斗士
    原文地址: https://segmentfault.com/a/1190000018344949
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞