This article describe the famious issue “function in loop and closure” in JavaScript.

The root cause is loop statements (such as for, while) don’t have their own scope.

Let’s see an example first:

    <ul><li>Item1</li><li>Item2</li><li>Item3</li></ul>
    var liNodes = document.getElementsByTagName("li");for (var i = 0; i < liNodes.length; i++) {liNodes[i].onclick = function() {alert("You click item " + i);};}

Now, if you click each of the list, all will produce a “You click item 3″ alert
box.

The number 3 comes out of the end execution of the loop (0, 1, 2 and out of the
loop i === 3).

Obviously, the result is not expected.

If you use JSLint to validate this piece of code, you will get the following warning:

Be careful when making functions within a loop. Consider putting the function in
a closure.

According to JSLint’s suggest, we have the first solution:

    // GOOD - 0function clickNode(liNode, i) {liNode.onclick = function() {alert("You click item " + i);};}  var liNodes = document.getElementsByTagName("li");for (var i = 0; i < liNodes.length; i++) {clickNode(liNodes[i], i);}

If you don’t want to create another function, consider using anonymous funtion:

    // GOOD - 1var liNodes = document.getElementsByTagName("li");for (var i = 0; i < liNodes.length; i++) {(function(i) {liNodes[i].onclick = function() {// You click item 0// You click item 1// You click item 2alert("You click item " + i);};})(i);}

Notice: The self-executing function create a context scope which contains a local
variable i.

When the click event occurs, the variable i is coming from the closure which is
just the self-executing function scope.

There are many ways to solve this problem, following are another three ways:

    // GOOD - 2var liNodes = document.getElementsByTagName("li");$.each(liNodes, function(i, item) {$(item).click(function() {// You click item 0// You click item 1// You click item 2alert("You click item " + i);});});  // GOOD - 3$("li").each(function(i, item) {$(item).click(function() {// You click item 0// You click item 1// You click item 2alert("You click item " + i);});});  // PREFERED - 4var liNodes = $("li").click(function(event) {var i = liNodes.index(this);// You click item 0// You click item 1// You click item 2alert("You click item " + i);});

转载于:https://www.cnblogs.com/sanshi/archive/2009/06/30/1514065.html

Function in loop and closure相关推荐

  1. Closure call with mismatched arguments: function ‘routes.<anonymous closure>‘

    Closure call with mismatched arguments: function 'routes.' 今天在玩flutter的时候,发现了个问题,以此记录一下: 在学习路由跳转的时候, ...

  2. php closure invoke,PHP Closure类详解

    PHP Closure 类是用于代表匿名函数的类,匿名函数(在 PHP 5.3 中被引入)会产生这个类型的对象,Closure类摘要如下: Closure { __construct ( void ) ...

  3. PHP学习笔记(一):理解匿名函数与Closure

    1.PHP里的匿名函数实质是Closure类的实例 (1)不能自己实例化Closure类型的对象,会触发一个Error try{$closure = new \Closure(); }catch(Er ...

  4. colsure php_PHP_PHP中Closure类的使用方法及详解,Closure,匿名函数,又称为Anonym - phpStudy...

    PHP中Closure类的使用方法及详解 Closure,匿名函数,又称为Anonymous functions,是php5.3的时候引入的.匿名函数就是没有定义名字的函数.这点牢牢记住就能理解匿名函 ...

  5. V-REP教程(七)API function

    浏览Regular API function list (by category) 1.文件操作类的 simSaveScene("a.ttt") 2.General object ...

  6. PHP Closure类详解

    PHP Closure 类是用于代表匿名函数的类,匿名函数(在 PHP 5.3 中被引入)会产生这个类型的对象,Closure类摘要如下: Closure {__construct ( void )p ...

  7. php closure 类,PHP中Closure类详解

    本文主要和大家分享PHP中Closure类详解,PHP Closure 类是用于代表匿名函数的类,匿名函数(在 PHP 5.3 中被引入)会产生这个类型的对象,Closure类摘要如下:Closure ...

  8. php closure invoke,php之closure(闭包)

    对于闭包(也叫匿名)的理解,只要记住一点就可以了:匿名是没有明确的名字进行定义的. 匿名函数 声明的格式如下: $func = function(){ };//带结束符 也可以带上形参,如下 $fun ...

  9. PHP Closure的用法

    Closure,匿名函数,是php5.3的时候引入的,又称为Anonymous functions.字面意思也就是没有定义名字的函数.比如以下代码(文件名是do.php) <?php funct ...

最新文章

  1. 谷歌年度AI技术总结来了!Jeff Dean执笔,附赠27个开源工具和数据大礼包
  2. vue指令写在html中的原理,详解Vue中的MVVM原理和实现方法
  3. [转]撞车之后,不要傻里傻气的!
  4. pat乙级相当于什么水平_林书豪在CBA相当于什么水平的外援?
  5. 文本二叉树折半查询及其截取值
  6. 资源放送丨《MySQL在某航空业公司的架构选型演进之路》PPT视频
  7. 【多线程】LockSupport 使用 原理 源码 分析
  8. void QWidget::update ()分析重绘事件激活
  9. 【文末福利】聊天机器人的几种主要架构实现
  10. python 实现读取txt 并画三维图
  11. L2-020. 功夫传人(STL+深搜)
  12. 百度人脸识别文档冲突,facetype应是face_type
  13. 删除AdminServer logs下的log文件后开启AdminServer报错
  14. 【19】蓝桥杯之奇妙的数字(填空题)
  15. Tableau学习教程(万字保姆级教程)​​​​​​
  16. Windows7系统环境变量path的配置方法
  17. 亚马逊多账号防关联的解决方式
  18. 数据分析师年薪50w起 人才缺口极大
  19. 程序员的损失!Erlang 之父 Joe Armstrong 离世
  20. 2019智能手表推荐_2020年买什么智能手表合适?

热门文章

  1. Oracle中的date与timestamp
  2. Redis的高级特性哨兵
  3. 进入编辑模式、vim命令模式、vim实践
  4. 字符串中连续出现最多的子串 amp; 字符串中最长反复子串
  5. Spring《二》 Bean的生命周期
  6. pt-table-checksum 原理解析
  7. OD调试9—实例:深入分析代码完成软件破解
  8. 新鲜出炉!20款好看的英文字体下载
  9. Visual studio中编译和使用libpng和zlib
  10. jenkins 添加 k8s 云