请解释闭包,或将循环计数器绑定到函数范围 [英] Please explain closures, or binding the loop counter to the function scope
问题描述
我见过程序员使用计数器在循环中分配事件监听器。我相信这是语法:
I've seen programmers assign events listeners inside loops, using the counter. I believe this is the syntax:
for(var i=0; i < someArray.length; i++){
someArray[i].onclick = (function(i){/* Some code using i */})(i);
}
有人可以解释这背后的逻辑, ve从未见过这个:
Could someone please explain the logic behind this, and this weird syntax, I've never seen this:
(function(i))(i);
非常感谢您的时间和耐心。
Many thanks for your time and patience.
推荐答案
这样做是因为JavaScript只有功能范围,而不是阻止范围。因此,你在一个循环中声明的每个变量都在函数的作用域中,你创建的每个闭包都可以访问同一个变量。
This is done because JavaScript only has function scope, not block scope. Hence, every variable you declare in a loop is in the function's scope and every closure you create has access to the very same variable.
因此,创建一个新的范围是调用一个函数,这是什么
So the only way to create a new scope is to call a function and that is what
(function(i){/* Some code using i */}(i))
正在做。
注意,你的例子缺少一个重要的部分:立即函数必须返回另一个函数,它将是点击
处理程序:
Note that your example misses an important part: The immediate function has to return another function which will be the click
handler:
someArray[i].onclick = (function(i){
return function() {
/* Some code using i */
}
}(i));
立即函数没有什么特别的。它是以某种方式内联函数定义和函数调用。您可以通过正常的函数调用替换它:
The immediate function is nothing special. It is somehow inlining function definition and function call. You can replace it by a normal function call:
function getClickHandler(i) {
return function() {
/* Some code using i */
}
}
for(var i=0; i < someArray.length; i++){
someArray[i].onclick = getClickHandler(i);
}
这篇关于请解释闭包,或将循环计数器绑定到函数范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!