从JavaScript闭包访问循环中的外部变量 [英] Access outside variable in loop from Javascript closure

查看:134
本文介绍了从JavaScript闭包访问循环中的外部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅:

for (var i in this.items) {
    var item = this.items[i];
    $("#showcasenav").append("<li id=\"showcasebutton_"+item.id+"\"><img src=\"/images/showcase/icon-"+item.id+".png\" /></li>");
    $("#showcasebutton_"+item.id).click(function() {
        alert(item.id);
        self.switchto(item.id);
    });
}

问题是警报的item.id总是最后一个数组中的项(this.items)。如何解决?

The problem is that the alerted item.id is always the id of the last item in the array (this.items). How to solve?

推荐答案

这里的问题是变量 item 每个循环改变。当稍后引用时,将使用其保存的最后一个值。您可以使用名为关闭的技术(基本上是一个返回一个函数的函数)来快速调整变量的范围。

The problem you have here is that the variable item changes with each loop. When you are referencing item at some later point, the last value it held is used. You can use a technique called a closure (essentially a function that returns a function) to quickly scope the variable differently.

    for (var i in this.items) {
            var item = this.items[i];
            $("#showcasenav").append("<li id=\"showcasebutton_"+item.id+"\"><img src=\"/images/showcase/icon-"+item.id+".png\" /></li>");
            $("#showcasebutton_"+item.id).click( 
                // create an anonymous function that will scope "item"
                (function(item) {
                   // that returns our function 
                   return function() {
                    alert(item.id);
                    self.switchto(item.id);
                   };
                })(item) // immediately call it with "item"
            );
    }

旁注 - 我看到你在这里有jQuery。它具有帮助函数 $。each() 可以与数组一起使用,并且可以是简单for / each循环的快捷方式。因为在这个调用中的范围工作方式 - 你不需要使用一个闭包,因为item已经是函数的参数,当它被调用时,不存储在 var

A side note - I see that you have jQuery here. It has a helper function $.each() that can be used with arrays, and can be a shortcut for simple for/each loops. Because of the way the scoping works in this call - you wont need to use a closure because "item" is already the parameter of the function when it was called, not stored in a var in the parent function's scope, like was true in your example.

$.each(this.items,function(i, item) {
  $("#showcasenav").append("<li id=\"showcasebutton_"+item.id+"\"><img src=\"/images/showcase/icon-"+item.id+".png\" /></li>");
  $("#showcasebutton_"+item.id).click(function() {
    alert(item.id);
    self.switchto(item.id);
  });
});

这篇关于从JavaScript闭包访问循环中的外部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆