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

最新文章

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

热门文章

  1. VS2015和QTcreator冲突解决办法
  2. Win/Lin 双系统时间错误的调整 (转)
  3. pythoner国内比较快 的 镜像源
  4. Exchange重启脚本
  5. JUC 之 ThreadPoolExecutor 的一些研究
  6. List 的一个有用的高效的操作 removeAll
  7. twisted reactor执行流程
  8. flex 上下div固定, 中间div自适应
  9. linux 文件系统之superblock
  10. linux 一个跟踪文件删除的小技巧