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);
}
看下执行效果:
如上图: 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)
}
写法二:
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);
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- 在缓存中使用闭包函数
- 在事务中使用闭包函数简化开发
- Java8 新语法习惯 (使用闭包捕获状态)
- 动手写一个简单的编译器:在 JavaScript 中使用 Swift 的尾闭包语法
- 草根学Python(十五) 闭包(解决一个需求了解闭包流程)
- [原]谈一谈闭包
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
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》 这本书的介绍吧!