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 ...
随机推荐
- 设置nginx中文件上传的大小限制度
通过设置nginx的client_max_body_size解决nginx+php上传大文件的问题: 用nginx来做webserver的时,上传大文件时需要特别注意client_max_body_s ...
- javafx链接实现
方式一: Desktop.getDesktop().browse(new URI(manualUrl)); 在linux环境bug 方式二: 转载自:https://stackoverflow.com ...
- RHEL yum
一.YUM源配置 使用RHEL自带的yum时会显示 #This system is not registered to Red Hat Subscription Management. You can ...
- 重识linux-仅执行一次的工作调动at
重识linux-仅执行一次的工作调动at 使用的是at命令 1 在系统中使用的是 atd这个服务 默认是不开启的 先启动 atd start 查看atd的状态 service atd status 2 ...
- 插件:★★★ !!!图片懒加载 lazyload.js 、 jquery.scrollLoading.js
插件:图片懒加载 jquery.lazyload.js 2016-3-31 插件说明:http://www.w3cways.com/1765.html (小插件,好用) 下载地址: https://r ...
- JS中点击事件冒泡阻止
JS中点击事件冒泡阻止 解析: 一个div层'out',内含有一个div层'in'.如下: 两个层都绑定了点击事件,但是点击in层的时候,点击事件会出现冒泡现象,同时也会触发out层的点击事件. 但是 ...
- 浅析STM32之usbh_def.H
[温故而知新]类似文章浅析USB HID ReportDesc (HID报告描述符) 现在将en.stm32cubef1\STM32Cube_FW_F1_V1.4.0\Middlewares\ST\S ...
- 机器学习入门-数值特征-进行多项式变化(将特征投影到高维度上) 1.PolynomialFeatures(将数据变化为多项式特征)
函数说明: 1. PolynomialFeatures(degree=2, interaction_only=False, include_bias=False) 参数说明:degree=2,表示多项 ...
- confusing c++ 重写 与 重定义 记录1
class parent { public: void f() { cout << "parent f()" << endl; } void f(int i ...
- ORM对单表的增删改查
表记录的增加: 1)b = Book(name='python', price=99) b.save() 2)Book.objects.create(name='python', price=99) ...