There are no differences in this example. In both cases it anotherFnis 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]);
}
}
Because JavaScript has only a scope of functions, without a block scope, all event handlers have the same ione that will matter 10after the loop finishes. Therefore, each handler will try to warn values[10].
, , "" :
for(var i from 1..10) {
(function(index) {
elements[i].onclick = function() {
alert(values[index]);
}
}(i));
}
, , , :
function getHandler(value) {
return function(){alert(value);};
}
for(var i from 1..10) {
elements[i].onclick = getHandler(values[i]);
}