Possible Duplicate:
Are “(function ( ) { } ) ( )” and “(function ( ) { } ( ) )” functionally equal in JavaScript?
My question having these special characters, I couldn't find a good answer. (Does anyone know how to search with them?)
I've seen two patterns to immediately calling anonymous functions http://jsfiddle.net/ukqS8/1/
(function(d) {
document.write(d*2);
})(3);
and
(function(x) {
document.write(x*2);
}(3));
The difference being where (3) is placed: inside or outside the closing parenthesis.
I found a good explanation for the second case here:
javascript function vs. ( function() { ... } ());
which I understood as function(x) {...}
creates a function object, (3) becomes its argument, and the enclosing () tells the interpreter that what's inside is a statement.
In the first case, it appears to make (function(d) {...})
a statement that somehow is also a function, and then apply (3) to this statement/function.
So, they both appear to execute the same way. Is there really a difference here? Scope (I doubt it)? Is either option preferable?