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 swing 代码例子

    package com; import java.awt.Button; import java.awt.Container; import java.awt.event.ActionEvent; i ...

  2. 笔记:js疑难复习

    apply 和 call的区别 call 和 apply 的区别只在于这两个函数接受的参数形式不同 var Person = function(name,age){ this.name = name; ...

  3. 浏览器和对象的dom属性

    1 DOM对象:var obj=document.getElementById('*'); obj.scrollWidth 是对象的实际内容的宽,不包边线宽度,会随对象中内容的多少改变(内容多了可能会 ...

  4. Android Netty Client

    Android netty client Start a netty client on android Download netty Download url :https://netty.io/d ...

  5. vue eslint 代码自动格式化

    vue-cli 代码风格为 JavaScript Standard Style 代码检查规范严格,一不小心就无法运行,使用eslint的autoFixOnSave可以在保存代码的时候自动格式化代码 V ...

  6. 机器学习入门-数值特征-数据四分位特征 1.quantile(用于求给定分数位的数值) 2.plt.axvline(用于画出竖线) 3.pd.pcut(对特征进行分位数切分,生成新的特征)

    函数说明: 1.  .quantile(cut_list) 对DataFrame类型直接使用,用于求出给定列表中分数的数值,这里用来求出4分位出的数值 2.  plt.axvline()  # 用于画 ...

  7. python 阿狸的进阶之路(6)

    常用模块 json # 序列化 #将内存的数据存到硬盘中,中间的格式,可以被多种语言识别,跨平台交互数据 #json 可以将字典之类的数据类型存到字典中 import json dic = {&quo ...

  8. jq动画分析

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  9. maven的环境变量配置

    一: 首先下载maven, 下载地址:http://maven.apache.org/download.html 打开这个连接:选择File下面的apache-maven-3.2.1-bin.zip链 ...

  10. NSTimer内存泄漏

    用NSTimer调用 timer = [NSTimer scheduledTimerWithTimeInterval:timerInterval target:self selector:@selec ...