JavaScript 如何使用闭包

栏目: JavaScript · 发布时间: 6年前

内容简介:闭包基本上是内部函数可以访问其范围之外的变量,可用于实现隐私和创建函数工厂如上图:

闭包基本上是内部函数可以访问其范围之外的变量,可用于实现隐私和创建函数工厂

定义一个数组,循环遍历这个数组并在延迟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 ,而不是 0 1 2 3

原因:因为 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 如何使用闭包


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Agile Web Application Development with Yii 1.1 and PHP5

Agile Web Application Development with Yii 1.1 and PHP5

Jeffrey Winesett / Packt Publishing / 2010-08-27

In order to understand the framework in the context of a real-world application, we need to build something that will more closely resemble the types of applications web developers actually have to bu......一起来看看 《Agile Web Application Development with Yii 1.1 and PHP5》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具