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的更多相关文章

  1. [Javascript] Closure Cove, Common mistake

    They’ve got a problem with their existing code, which tries to use a closure. Check it out: function ...

  2. Go xmas2020 学习笔记 06、Control Statements、Declarations & Types

    06-Control Statements. If-then-else. Loop. for. range array. range map. infinite loop. common mistak ...

  3. [转]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 ...

  4. 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 ...

  5. Unity 5 Game Optimization (Chris Dickinson 著)

    1. Detecting Performance Issues 2. Scripting Strategies 3. The Benefits of Batching 4. Kickstart You ...

  6. Go 1 Release Notes

    Go 1 Release Notes Introduction to Go 1 Changes to the language Append Close Composite literals Goro ...

  7. linux内核的makefile.txt讲解

    linux内核的linux-3.6.5\Documentation\kbuild\makefiles.txt Linux Kernel Makefiles This document describe ...

  8. (转)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 ...

  9. Linux内核Makefile文件(翻译自内核手册)

    --译自Linux3.9.5 Kernel Makefiles(内核目录documention/kbuild/makefiles.txt) kbuild(kernel build) 内核编译器 Thi ...

随机推荐

  1. 转:Java对象序列化

    Java对象序列化 当两个进程在进行远程通信时,彼此可以发送各种类型的数据.无论是何种类型的数据,都会以二进制序列的形式在网络上传送.发送方需要把这个Java对象转换为字节序列,才能在网络上传送:接收 ...

  2. 阿里云实现putty私钥登录全过程

    阿里云实现putty私钥登录全过程 1 putty生成公钥和私钥 1)putty生成公钥和私钥 记得在空白区域 滑动 2 公钥上传到阿里云 1)公钥上传  私钥存到本地 3 公钥绑定要登录的实例 4 ...

  3. python学习笔记_week13

    一.前景介绍 到目前为止,很多公司对堡垒机依然不太感冒,其实是没有充分认识到堡垒机在IT管理中的重要作用的,很多人觉得,堡垒机就是跳板机,其实这个认识是不全面的,跳板功能只是堡垒机所具备的功能属性中的 ...

  4. 关于IK 分词器

    准备: 1 创建索引: PUT my_index PUT my_index2 2 先做好映射: PUT /my_index/*/_mapping { "properties": { ...

  5. delphi 动态绑定代码都某个控件

    delphi 动态绑定代码都某个控件 http://docwiki.embarcadero.com/CodeExamples/Berlin/en/Rtti.TRttiType_(Delphi)Butt ...

  6. hive理论

    join操作: 这个 group by count()操作: 数据倾斜: 操作• Join on a.id=b.id• Group by• Count Distinct count(groupby)• ...

  7. RocketMQ服务搭建_1

    rocketmq是阿里研发,并贡献给Apache的一款分布式消息中间件. RcoketMQ 是一款低延迟.高可靠.可伸缩.易于使用的消息中间件. ACE环境:(Adapted communicatio ...

  8. compose配置文件参数详解

    转自:https://www.cnblogs.com/jsonhc/p/7814138.html 本文介绍compose配置文件参数的使用,熟练编写compose文件 [root@docker lnm ...

  9. myeclipse提示错误。

    Syntax error, parameterized types are only available if source level is 1.5 解决方法:编译器问题.注意myeclipse10 ...

  10. 剑指offer例题——旋转数组的最小数字

    题目:把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转. 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素. 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转, ...