如何解决Javascript闭包? [英] How can I work around the Javascript closures?

查看:78
本文介绍了如何解决Javascript闭包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下JavaScript小片段:

Consider this small snippet of JavaScript:

for(var i in map.maps)
{
    buttons.push($("<button>").html(i).click(function() { alert(i); }));
}

它为 map.maps 对象(这是一个assoc数组)中的每个字段创建一个按钮.我将索引设置为按钮的文本,并将其设置为也警告索引.显然,人们希望所有按钮在单击时都会提示自己的文本,但相反,所有按钮都会在单击时在 map.maps 对象中的 final 索引文本中发出警报.

It creates one button for each of the fields in the map.maps object (It's an assoc array). I set the index as the button's text and set it to alert the index as well. Obviously one would expect all the buttons to alert it's own text when clicked, but instead all the buttons alert the text of the final index in the map.maps object when clicked.

我认为此行为是由JavaScript处理闭包,从创建闭包的函数返回并执行函数的巧妙方式引起的.

I assume this behavior is caused by the neat way JavaScript handles closures, going back and executing functions from the closures in which they were created.

我能想到的解决此问题的唯一方法是将索引设置为按钮对象上的数据,并在click回调中使用它.我也可以在我的 buttons 对象中模仿 map.maps 索引,并使用 indexOf 在单击时找到正确的索引,但是我更喜欢前一种方法

The only way I can imagine getting around this is setting the index as data on the button object and using it from the click callback. I could also mimic the map.maps indices in my buttons object and find the correct index on click using indexOf, but I prefer the former method.

我在寻找答案的目的是确认我正在以正确的方式进行操作,或者是关于我应该如何进行操作的建议.

What I'm looking for in answers is confirmation that I'm doing it the right way, or a suggestion as to how I should do it.

推荐答案

拥抱闭包,不要绕开它们.

Embrace the closures, don't work around them.

for(var i in map.maps)
{
    (function(i){
        buttons.push($("<button>").html(i).click(function() { alert(i); }));
    })(i);
}

您需要包装使用var i的代码,以便将其结尾在单独的闭包中,并将值保存在该闭包的本地var/param中.

You need to wrap the code that uses your var i so that it ends up in a separate closure and the value is kept in a local var/param for that closure.

使用类似lonesomeday的答案的单独功能可以稍微隐藏这种闭合行为,但同时更加清晰.

Using a separate function like in lonesomeday's answer hides this closure behaviour a little, but is at the same time much clearer.

这篇关于如何解决Javascript闭包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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