问题描述
在我想这样做的网站上:(简化)
on a website i want to do this: (simplified)
myHandlers = new Array();
for(var i = 0; i < 7; i++) {
myHandlers.push(new Handler({
handlerName: 'myHandler'+i, // works, e.g. ->myHandler1, 2, 3 etc.
handlerFunc: function(bla) { /*...*/ alert(i); } // doesn't work,all return 7
}
}
我可以将计数器设置为我的 Handler 的另一个属性(它将复制当前值)并在我的函数中使用它,但我想,还有一种方法可以实际复制这个值,不是吗?
I could set the counter as another attribute of my Handler (which would copy the current value) and use it inside my function, but I guess, there is also a way to actually copy this value, no?
推荐答案
当调用handlerFunc时,函数内部的i
指的是i
for
循环的代码>.但是那个 i
可能不再具有相同的值了.
When handlerFunc is called, the i
inside the function refers to the i
of the for
loop. But that i
does probably not have the same value any more.
使用闭包将 i
的当前值绑定到匿名函数的范围内:
Use a closure to bind the current value of i
in the scope of an anonymous function:
handlerFunc: (function(i) { return function(bla) { /*...*/ alert(i); }; })(i)
这里使用了一个匿名函数 (function(i) { … })(i)
并立即调用.该函数将 for
循环的 i
的值绑定到本地 i
.该 i
然后独立于 for
循环的 i
.
Here an anonymous function (function(i) { … })(i)
is used and called immediately. This function binds the value of i
of the for
loop to the local i
. That i
is then independent from the i
of the for
loop.
这篇关于javascript:在函数(){}中使用当前的for循环计数器值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!