闭包

120 阅读1分钟

闭包是指外部作用域访问内部作用域变量

闭包只需要理解两个点:

  • 在函数内部定义函数
  • 函数不调用不执行

编写一个函数,该函数将遍历整数列表,并在延迟3秒后打印每个元素的索引

//方法一
for (var i = 0; i < arr.length; i++) {
    setTimeout(function(i_local) {
      return function() {
        console.log('The index of this number is: ' + i_local);
      };
    }(i), 3000);
}
//方法二
for (let i = 0; i < arr.length; i++) {
  setTimeout(function() {
    console.log('The index of this number is: ' + i);
  }, 3000);
}
//立即执行
for (let i = 0; i < arr.length; i++) {
  setTimeout(Index(i), 3000);
}
function Index(i) {
  console.log('The index of this number is: ' + i);
}