Javascript关闭 [英] Javascript closure
问题描述
我在闭包结束时读取()会立即执行它。那么,这两者之间有什么区别。我在一些代码中看到了第一次使用。
I read the () at the end of the closure will execute it immediately. So, what is the difference between these two. I saw the first usage in some code.
谢谢。
for (var a=selectsomeobj(),i=0,len=a.length;i<len;++i){
(function(val){
anotherFn(val);
})(a[i]);
}
for (var a=selectsomeobj(),i=0,len=a.length;i<len;++i){
anotherFn(a[i]);
}
推荐答案
在这个例子中没有差异。在这两种情况下, anotherFn
立即执行。
In this example there are no differences. In both cases, anotherFn
gets executed immediately.
但是,创建函数时通常会使用立即函数循环。
However, an immediate function is often used when a function is created in a loop.
考虑这个例子(或多或少的伪代码):
Consider this example (more or less pseudo code):
for(var i from 1..10) {
elements[i].onclick = function() {
alert(values[i]);
}
}
由于JavaScript只有函数作用域,没有块作用域,所有事件处理程序共享相同的 i
,在循环结束后将具有值 10
。因此每个处理程序都会尝试提醒值[10]
。
As JavaScript has only function scope, no block scope, all the event handlers share the same i
, which will have the value 10
after the loop finished. So every handler will try to alert values[10]
.
通过使用立即函数,新范围是介绍了捕获循环变量的当前值:
By using an immediate function, a new scope is introduced which "captures" the current value of the loop variable:
for(var i from 1..10) {
(function(index) {
elements[i].onclick = function() {
alert(values[index]);
}
}(i));
}
由于这有时难以阅读,因此创建一个返回另一个函数的独立函数通常更好:
As this is sometimes hard to read, creating a standalone function which returns another function is often better:
function getHandler(value) {
return function(){alert(value);};
}
for(var i from 1..10) {
elements[i].onclick = getHandler(values[i]);
}
这篇关于Javascript关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!