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. StanFord ML 笔记 第一部分

    本章节内容: 1.学习的种类及举例 2.线性回归,拟合一次函数 3.线性回归的方法: A.梯度下降法--->>>批量梯度下降.随机梯度下降 B.局部线性回归 C.用概率证明损失函数( ...

  2. MySQL Developer

    1.The mysql Client Program 2.Data Types 3.Joins 4.Subqueries 5.Views 6.StoredRoutine . 1.Client/Serv ...

  3. uva-270-排序

    题意:很多个点,问,最多有多少个点在同一条直线上 #include <algorithm> #include <iostream> #include <string> ...

  4. linux系统安全更新

    um --security upgrade 一.参考文档:  https://blog.csdn.net/ubuntu64fan/article/details/80927212 二.Linux主机定 ...

  5. Python基础4 迭代器、装饰器、软件开发规范

    本节内容 迭代器&生成器 装饰器 Json & pickle 数据序列化 软件目录结构规范 作业:ATM项目开发 1.列表生成式,迭代器&生成器 列表生成式 孩子,我现在有个需 ...

  6. NFS服务基本配置及使用

    操作系统:redhat 7.2 参考链接:https://www.cnblogs.com/dscode/p/6146409.html NFS:Network File System 一.服务器端配置 ...

  7. 【ASP.NET 插件】分享一个可视化HTML编辑器 CKEditor.NET

    因为公司网站的可视化HTML编辑器IE兼容性问题,js报错不能使用,于是在网上找到了个还行的,图片本地上传的话直接把图片拖到编辑窗口就可以了.这个编辑器是在开源中国看到的,个人觉得还不错! CKEdi ...

  8. ThinkPHP输入验证和I方法使用

    在Web开发过程中,我们经常需要获取系统变量或者用户提交的数据,这些变量数据错综复杂,而且一不小心就容易引起安全隐患,但是如果利用好ThinkPHP提供的变量获取功能,就可以轻松的获取和驾驭变量了. ...

  9. spring boot 的常用注解

    SpringBoot用于简化Spring应用的搭建,开发及部署:该框架采用注解的方式进行配置可以很方便的构建Spring应用. 1. @SpringBootApplication @SpringBoo ...

  10. Web安全颜色

    Web安全色产生的原因 不同的平台(Mac.PC等)有不同的调色板,不同的浏览器也有自己的调色板.这就意味着对于一幅图,显示在Mac上的Web浏览器中的图像,与它在PC上相同浏览器中显示的效果可能差别 ...