当使用局部变量将匿名函数传递给命名函数时,Javascript中的范围问题 [英] Scope troubles in Javascript when passing an anonymous function to a named function with a local variable
问题描述
对标题感到抱歉 - 我无法想出一个方法来表达它。
Sorry about the title - I couldn't figure out a way to phrase it.
这是一个场景:
我有一个构建元素的函数:
I have a function that builds a element:
buildSelect(id,cbFunc,...)
在buildSelect内部执行此操作:
Inside buildSelect it does this:
select.attachEvent('onchange',cbFunc);
我还有一个数组:
var xs = ['x1','x2','x3'...];
鉴于所有这些,我有一些代码可以做到这一点:
Given all of these, I have some code that does this:
for(var i = 0; i < xs.length; i++)
{
buildSelect(blah,function(){ CallBack(xs[i],...) },...);
}
问题是,当onchange被其中一个选项触发时,它正确地去了到CallBack()但第一个参数不正确。例如,如果我改变第三个选择,我期望用xs [2]调用CallBack(),而不是像xs [3]或其他东西那样得到一些不同的东西。
The issue is that when onchange gets fired on one of those selects it correctly goes to CallBack() but the first parameter is incorrect. For example if I change the third select I expect CallBack() to be called with xs[2] instead I get some varying things like xs[3] or something else.
如果我稍微修改它:
for(var i = 0; i < xs.length; i++)
{
var xm = xs[i];
buildSelect(blah,function(){ CallBack(xm,...) },...);
}
我在CallBack()中的值仍然不正确。有些东西告诉我这是范围/关闭相关但我似乎无法弄清楚是什么。
I'm still getting incorrect values in CallBack(). Something tells me this is scope/closure related but I can't seem to figure out what.
我只想让第一个选择调用CallBack for onchange,第一个参数为xs [0],第二个选择用xs [1],依此类推。我在这里可能做错了什么?
I simply want the first select to call CallBack for onchange with the first parameter as xs[0], the second select with xs[1] and so on. What could I be doing wrong here?
我应该澄清xs是一个全局变量。
I should clarify that xs is a global variable.
谢谢
推荐答案
您需要通过在其中关闭它来捕获 xm
值自己的范围。
You need to capture that xm
value by closing around it in its own scope.
要做到这一点,需要单独的函数调用:
To do this requires a separate function call:
buildCallback( curr_xm ) {
// this function will refer to the `xm` member passed in
return function(){ CallBack(curr_xm,...) },...);
}
for(var i = 0; i < xs.length; i++)
{
var xm = xs[ i ];
buildSelect(blah,buildCallback( xm ),...);
}
现在 xm
回调引用的是您传递给 buildCallback
的那个。
Now the xm
that the callback refers to is the one that you passed to buildCallback
.
如果你还需要保留 i
的其他用途,你可以发送它:
If you have other uses for i
that need to be retained, you could send that instead:
buildCallback( curr_i ) {
// this function will refer to the `i` value passed in
return function(){ CallBack( xs[ curr_i ],...) },...);
}
for(var i = 0; i < xs.length; i++)
{
buildSelect(blah,buildCallback( i ),...);
}
这篇关于当使用局部变量将匿名函数传递给命名函数时,Javascript中的范围问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!