JavaScript函数问题
我进行了搜索,但找不到这个看似简单问题的答案,所以......
假设我有一个循环,需要在其中设置回调。我的回调函数看起来像这样:
function callback(var1) { // code }
现在我的循环是这样的:
for( //condition)
{
var x = something_different_each_time;
document.getElementById('foo').addEventListener('click', function() { callback(x); }, false);
}
现在看起来即使循环运行 n 次,匿名函数也只编译一次 - 因此每次调用回调时都会使用相同的参数(甚至尽管 x 每次在循环中都会变化)。
我一定在这里遗漏了一些东西..非常感谢任何帮助! :)
I searched but couldn't find an answer to this seemingly easy question, so...
Suppose I have a loop in which I need to set callbacks. My callback function looks like this:
function callback(var1) { // code }
Now my loop is something like this:
for( //condition)
{
var x = something_different_each_time;
document.getElementById('foo').addEventListener('click', function() { callback(x); }, false);
}
Now it looks like even if the loop runs n times, the anonymous function is compiled only once -- and hence every invocation of callback is called with the same argument (even though x varies in the loop every time).
I must be missing something here.. any help is greatly appreciated! :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
问题是 for 语句块没有创建新的作用域,为此,x 变量属于其封闭作用域,并且所有匿名函数都引用相同的变量...
使用另一个函数创建一个新的词法环境以在每次迭代时保存
x
的值:The problem is that the block of the
for
statement doesn't creates a new scope, for that, thex
variable belongs to its enclosing scope, and all anonymous functions refer to the same variable...Use another function to create a new lexical environment to hold the value of
x
on each iteration:请参阅在循环中创建闭包:常见错误
和相关问题:
See Creating closures in loops: A common mistake
and related questions:
您应该在调用回调函数之前计算 x!
You should calculate x before calling your callback functin!
是的,
x
将引用封闭范围内的同一变量,并且由于该函数稍后执行,因此它将具有x
的最后一个值。试试这个:这会创建一个闭包,其中锁定了
x
的当前值。Yes, the
x
will refer to the same variable in the enclosing scope, and since the function is executing later, it'll have the last value ofx
. Try this:This creates a closure with the current value of
x
locked inside.