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

查看:39
本文介绍了从 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 总是数组中最后一个项目的 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 随每个循环而变化.当您稍后引用 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天全站免登陆