common mistake of closure in loops
【common mistake of closure in loops】
下例中item引用的始终是最后一个值。
function showHelp(help) {
document.getElementById('help').innerHTML = help;
}
function setupHelp() {
var helpText = [
{'id': 'email', 'help': 'Your e-mail address'},
{'id': 'name', 'help': 'Your full name'},
{'id': 'age', 'help': 'Your age (you must be over 16)'}
];
for (var i = 0; i < helpText.length; i++) {
var item = helpText[i];
document.getElementById(item.id).onfocus = function() {
showHelp(item.help);
}
}
}
setupHelp();
解法一:callback时,加一层closure以保留item状态
function showHelp(help) {
document.getElementById('help').innerHTML = help;
}
function makeHelpCallback(help) {
return function() {
showHelp(help);
};
}
function setupHelp() {
var helpText = [
{'id': 'email', 'help': 'Your e-mail address'},
{'id': 'name', 'help': 'Your full name'},
{'id': 'age', 'help': 'Your age (you must be over 16)'}
];
for (var i = 0; i < helpText.length; i++) {
var item = helpText[i];
document.getElementById(item.id).onfocus = makeHelpCallback(item.help);
}
}
setupHelp();
解法二:loop时,加一层closure以保留item状态
function showHelp(help) {
document.getElementById('help').innerHTML = help;
}
function setupHelp() {
var helpText = [
{'id': 'email', 'help': 'Your e-mail address'},
{'id': 'name', 'help': 'Your full name'},
{'id': 'age', 'help': 'Your age (you must be over 16)'}
];
for (var i = 0; i < helpText.length; i++) {
(function() {
var item = helpText[i];
document.getElementById(item.id).onfocus = function() {
showHelp(item.help);
}
})(); // Immediate event listener attachment with the current value of item (preserved until iteration).
}
}
setupHelp();
解法三:使用let
function showHelp(help) {
document.getElementById('help').innerHTML = help;
}
function setupHelp() {
var helpText = [
{'id': 'email', 'help': 'Your e-mail address'},
{'id': 'name', 'help': 'Your full name'},
{'id': 'age', 'help': 'Your age (you must be over 16)'}
];
for (var i = 0; i < helpText.length; i++) {
let item = helpText[i];
document.getElementById(item.id).onfocus = function() {
showHelp(item.help);
}
}
}
setupHelp();
参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
common mistake of closure in loops的更多相关文章
- [Javascript] Closure Cove, Common mistake
They’ve got a problem with their existing code, which tries to use a closure. Check it out: function ...
- Go xmas2020 学习笔记 06、Control Statements、Declarations & Types
06-Control Statements. If-then-else. Loop. for. range array. range map. infinite loop. common mistak ...
- [转]50 Shades of Go: Traps, Gotchas, and Common Mistakes for New Golang Devs
http://devs.cloudimmunity.com/gotchas-and-common-mistakes-in-go-golang/ 50 Shades of Go: Traps, Gotc ...
- Yet Another 10 Common Mistakes Java Developers Make When Writing SQL (You Won’t BELIEVE the Last One)--reference
(Sorry for that click-bait heading. Couldn’t resist ;-) ) We’re on a mission. To teach you SQL. But ...
- Unity 5 Game Optimization (Chris Dickinson 著)
1. Detecting Performance Issues 2. Scripting Strategies 3. The Benefits of Batching 4. Kickstart You ...
- Go 1 Release Notes
Go 1 Release Notes Introduction to Go 1 Changes to the language Append Close Composite literals Goro ...
- linux内核的makefile.txt讲解
linux内核的linux-3.6.5\Documentation\kbuild\makefiles.txt Linux Kernel Makefiles This document describe ...
- (转)A Survival Guide to a PhD
Andrej Karpathy blog About Hacker's guide to Neural Networks A Survival Guide to a PhD Sep 7, 2016 T ...
- Linux内核Makefile文件(翻译自内核手册)
--译自Linux3.9.5 Kernel Makefiles(内核目录documention/kbuild/makefiles.txt) kbuild(kernel build) 内核编译器 Thi ...
随机推荐
- js语法规则 ---console.log ---- prompt ----基本类型 ---parseInt
在页面中可以在body里面加入type=”text/javascript” 例如: <script type="text/javascript"> </scrip ...
- Java并发编程:Java Thread方法join的简单总结
虽然关于讨论线程join方法的博客已经很多了,不过个人感觉挺多都讨论得不够全面,所以我觉得有必要对其进行一个全面的总结. 一.作用 Thread类中的join方法的主要作用就是同步,它可以使得线程之间 ...
- spring boot js 文件引用 单引问题。
首页 index.html 访问首页空白 . F12 控制台看页面元素布局.发现有两个body 标签 ,而且 </head> 标红. 各种检查....好像是没有问题. 但就是访问空白.去掉 ...
- dom编程艺术章12
function addLoadEvent(func){//添加事件函数 var oldonload = window.onload; if(typeof window.onload != 'func ...
- 2. oracle创建表空间、用户并设置默认表空间、授权
1.创建用户并设置默认表空间 create tablespace tablespacename datafile 'tablespacename.dbf' size 200m autoextend o ...
- List去重问题引出来的hashCode和equals方法
一.List 里面是基本类型的去重问题 import java.util.ArrayList; import java.util.HashSet; import java.util.List; imp ...
- ssm框架之配置日志系统打印到控制台与指定文件
前提: 0:ssm框架已经搭建并且成功运行 1.maven环境配置成功 2.tomcat配置成功,并且配置本机的tomcat环境变量 内容: 0.导入所需要的jar包 <!-- 配置log4j日 ...
- Raft算法和Gossip协议
简单介绍下集群数据同步,集群监控用到的两种常见算法. Raft算法 raft 集群中的每个节点都可以根据集群运行的情况在三种状态间切换:follower, candidate 与 leader.lea ...
- Who am I?
陈治宏. 一只想做软件开发,但还在machine learning领域挣扎的计算机汪.
- while 循环居然可以用else
while 循环居然可以用else python 3 while a<50: print a a=a+1 else: print"over."