为了账号安全,请及时绑定邮箱和手机立即绑定

Function in loop and closure

标签:
资讯

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 - 0    function 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 - 1    var 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 2                alert("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 - 2    var liNodes = document.getElementsByTagName("li");    $.each(liNodes, function(i, item) {        $(item).click(function() {            // You click item 0            // You click item 1            // You click item 2            alert("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 2            alert("You click item " + i);        });    });      // PREFERED - 4    var liNodes = $("li").click(function(event) {        var i = liNodes.index(this);        // You click item 0        // You click item 1        // You click item 2        alert("You click item " + i);    });
点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消