common mistake of closure in loops
2024-10-19 07:27:47
【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
最新文章
- 2D banner
- JavaSE基础知识总结
- iOS中NSScanner 的用法
- mysql 查询技巧
- Android 返回键双击退出程序
- ThreadLocal的使用及介绍
- 设计模式之十三:适配器模式(Adapter)
- Duanxx的图像处理学习: 透视变换(一)
- MemoryBarrier,Volatile
- window编程之win程序框架
- Android软键盘事件imeOptions响应
- Python单元测试框架unittest
- JAVA实训第三次作业
- -bash: 未预期的符号 `(&#39; 附近有语法错误
- 优化网站设计(七):避免在CSS中使用表达式
- js数组遍历some、foreach、map、filter、every、lastIndexOf、indexOf对比
- 有关keras(Ubuntu14.04,python2.7)
- C#管理windows服务
- 腾讯云HTTPS设置管理
- poj1463 Strategic game【树形DP】