博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JavaScript 如何使用闭包
阅读量:6937 次
发布时间:2019-06-27

本文共 871 字,大约阅读时间需要 2 分钟。

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

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

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

转载地址:http://rbbnl.baihongyu.com/

你可能感兴趣的文章
从零开始-打造自己的虚拟实验室-2
查看>>
js 完美兼容浏览器的复制功能
查看>>
jdk1.6下使用sardine和jackrabbit-webdav的问题
查看>>
[Unity3d]socket通信 切换到web版本时报错SecurityException解决办法
查看>>
[Unity3D插件]2dtoolkit系列二 动画精灵的创建以及背景图的无限滚动
查看>>
谈谈spring中bean的名字
查看>>
Vue Element表单绑定(二)表单验证1
查看>>
Unix sed笔记
查看>>
macOS 10.12.x + Dell P2416D开启自定义 HiDPI
查看>>
图灵奖简介、2012年图灵奖得主及其贡献领域简介
查看>>
小工具推荐
查看>>
TiFlash & TiSpark?那都是 AP 团队开的坑 !
查看>>
(荷兰)彼得·冯·门施:博物馆学的研究对象
查看>>
我的友情链接
查看>>
查看Chrome浏览器缓存的方法
查看>>
Kubernetes权威指南之Kubernetes API详解
查看>>
修改windows service的启动类型
查看>>
***工具集合
查看>>
限流熔断技术选型:从Hystrix到Sentinel
查看>>
python写入和读取csv文件
查看>>