Reputation: 58662
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]);
}
Upvotes: 3
Views: 513
Reputation: 816452
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]);
}
}
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]);
}
Upvotes: 14
Reputation: 17825
In both instances in your example the values do identical operations. There are other examples out there where if you're not careful to use the first method (with the self-executing anonymous function), the value of i
will increment and not be passed correctly to your function.
Here's a guide, scroll down to the creating closures in loops: a common mistake section to see the problem:
https://developer.mozilla.org/en/JavaScript/Guide/Closures
Upvotes: 3
Reputation: 120198
the first defines a self-invoking function (which in turn executes a function), the second just executes the function. In both cases the argument passed to the is a[i].
Upvotes: 1