惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

W
WeLiveSecurity
The GitHub Blog
The GitHub Blog
Engineering at Meta
Engineering at Meta
Microsoft Azure Blog
Microsoft Azure Blog
The Register - Security
The Register - Security
Stack Overflow Blog
Stack Overflow Blog
博客园 - 三生石上(FineUI控件)
T
Threat Research - Cisco Blogs
S
SegmentFault 最新的问题
V2EX - 技术
V2EX - 技术
Hacker News: Ask HN
Hacker News: Ask HN
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
P
Proofpoint News Feed
J
Java Code Geeks
Microsoft Security Blog
Microsoft Security Blog
M
MIT News - Artificial intelligence
AI
AI
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
P
Proofpoint News Feed
Hacker News - Newest:
Hacker News - Newest: "LLM"
B
Blog
N
News and Events Feed by Topic
N
News | PayPal Newsroom
Google DeepMind News
Google DeepMind News
酷 壳 – CoolShell
酷 壳 – CoolShell
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
WordPress大学
WordPress大学
C
Cybersecurity and Infrastructure Security Agency CISA
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 【当耐特】
U
Unit 42
腾讯CDC
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
The Cloudflare Blog
H
Help Net Security
Recent Announcements
Recent Announcements
P
Privacy & Cybersecurity Law Blog
IT之家
IT之家
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Security Archives - TechRepublic
Security Archives - TechRepublic
L
LINUX DO - 热门话题
Martin Fowler
Martin Fowler
MongoDB | Blog
MongoDB | Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
H
Heimdal Security Blog
博客园 - 聂微东
S
Securelist
大猫的无限游戏
大猫的无限游戏
Cloudbric
Cloudbric
Cisco Talos Blog
Cisco Talos Blog

博客园 - 迷

如何升级一台老macbook air的macOS到最新版本 IDEA错误的忽略了智能补全代码,导致正确的代码自动提示不出来的问题 校准liunx时间简单好用的命令 服务器安装Ubuntu的那些坑 Activiti 乱码问题 Activiti 整合的小插曲 IDEA 提示找不到 javax 等 tomcat 的相关包 一些好用的 Oracle 批处理和语句 Oracle 日志报错导致的 “没有登录” 问题 WebPack 从安装到闲置 Android Studio 编译提示 No installed build tools found. Please install the Android build tools VBox 安装 Ubuntu Server 的那些坑,键盘乱码、网卡互连、共享目录等 nginx 的 upstream timed out 问题 产品是什么? 如何管理? 如何远程工作? 远程工作的手段 PhoneGap 3.4 开发配置及问题 错误:找不到或无法加载主类
闭包的应用案例
· 2017-12-08 · via 博客园 - 迷

闭包的应用案例

2017-12-08 20:19    阅读(172)  评论()    收藏  举报

1、如何在循环中给事件中的变量赋值

for (var i = 0; i < 10; i++) { //给按钮btn1 - btn10弹出一个序号提示框

  $('.btn' + i).click(function() {

    alert(i); //当我们给一个控件组附加事件时,想当然的会这样做

  });

}

但实际点所有按钮都只会弹出显示“9”,也很容易想明白,i 作为一个变量在循环中不断被改变,最终alert时自然只能得到 i 当前的值。

我们知道 (function() {})(); 这种形式的函数会被立刻实行,并形成一个闭包,那么利用这个原理用闭包解决办法如下:

for (var i = 0; i < 10; i++) { //给按钮btn1 - btn10弹出一个序号提示框

  (function(j) {

    $('.btn' + j).click(function() {

      alert(j); //此时这是匿名方法形成了一个闭包,i 传进来后就被本地化了,与外部的 i 值再无关联

    })

  })(i);

}

深入思考一下,在第一个例子中照理说 i 在循环结束后应该被释放,但因为事件中用到了,于是 for 循环中的 i 其实也形成了一个闭包,这就是为什么异步事件的事件中还能取到 i 的值。