闭包和js事件执行机制简介
最近碰到了关于闭包的问题,查看资料总结下我眼中的闭包
var price=document.getElementsByTagName('div');
for (var i = 0; i < 6; i++) {
price[i].onClick=function () {
console.log(i)
}
} // 6 6 6 6 6 6
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
先了解下js的执行机制,这里涉及了JS中单线程的概念。由于JS是单线程语言,不存在并发执行的任务,所有任务都需要排队,前一个任务结束,才会开始下一个任务。因此,在JS中,任务分为两种,一是同步任务,一是异步任务。而for循环就是同步任务,点击事件函数是异步任务,异步任务会去排队,排到同步任务的后面(大家猜猜如果几个异步任务排队顺序是怎样的),ok !
现在代码其实可以等于
var price=document.getElementsByTagName('div');
for (var i = 0; i < 6; i++) {
price[i].onClick=order();
}
fnction order(){
console.log(i)
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
然后了解什么是闭包,我理解的闭包就是在函数这个作业域里引用作用域之外的量,闭包有个特点就是–基于词法作用域的查找规则(当前找不到某个变量,就向上查找,如果最终没有找到,则返回undefined)。
所以,order()中的 i 就成了6,好了,小伙伴们了解了吧
,
</div><div data-report-view="{"mod":"1585297308_001","dest":"https://blog.****.net/weixin_44989478/article/details/105594964","extend1":"pc","ab":"new"}"><div></div></div>
<link href="https://****img.cn/release/phoenix/mdeditor/markdown_views-60ecaf1f42.css" rel="stylesheet">
</div>
</article>
关于微信小程序中组件和页面对全局样式的继承性
创建Java程序并设置快捷提示
微信小程序设置全局字体
微信小程序组件的使用
微信开发者工具的一些快捷键
消除flex-wrap之后每个item上下的距离
flex布局中的主轴和侧轴的确定
C++string中用于查找的find系列函数浅析
C++11 图说VS2013下的引用叠加规则和模板参数类型推导规则
- 最新文章
-
Spring Bean 生命周期
java字符串格式化
<context:component-scan>
Properties
classpath获取--getResource()
Spring的PropertyPlaceholderConfigurer应用
@Value 注解获取properties值
<context:annotation-config> 和 <context:component-scan>的区别
CSS 学习笔记
swift 2.x学习笔记(三)
- 热门文章
-
swift 2.x学习笔记(二)
swift 2.x学习笔记(一)
shader三种变量类型(uniform,attribute和varying)
mongod 命令执行发现已经有进程在运行mongod数据库--errno:48 Address already in use for socket: 0.0.0.0:27017
mongodb 安装与启动简单使用
mongodb 安装后 出现警告:** WARNING: soft rlimits too low. Number of files is 256, should be at least 1000
cordova-sqlite-plugin常用数据库操作
自己用node.js 搭建APP服务器,然后用AFNetworking 请求 报如下错误:App TransportSecurity has blocked a cleartext HTTP (http://) resource load since it isinsecure. Temporary exceptions can be configured via your app's Info.
微信小程序请求数据
微信小程序使用三元表达式切换图片