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.
thanks.
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]);
}
In this example there are no differences. In both cases,
anotherFngets 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):
As JavaScript has only function scope, no block scope, all the event handlers share the same
i, which will have the value10after the loop finished. So every handler will try to alertvalues[10].By using an immediate function, a new scope is introduced which “captures” the current value of the loop variable:
As this is sometimes hard to read, creating a standalone function which returns another function is often better: