Revealing the module template initialization style
I was wondering what is the meaning of the extra parenthesis when initializing an object. For example:
var foo = function(){ ... }();
against
var foo = (function(){ ... }());
I'm guessing it has something to do with scope, but I was wondering if anyone could clarify the specific differences as they both seem to initialize an object based on the return of each anonymous function.
source to share
There is no effective difference in this particular case.
Some people like the external (...)
one because it gives them a visual hint next to the operator =
calling the function.
But the assignment operator invokes the evaluation function
as an expression, which is the right-hand operand of the assignment operator, and as such it can be called without any additional need to force it from the function declaration.
Without assignment, some syntax is required to let the interpreter know that the keyword is being function
used as an anonymous function expression.
For example...
(function() {
// code
})();
Here, the parentheses allowed ambiguity function
so that it was treated as a single expression within the group (...)
.
The grouping operator is just one way to make it function
evaluate as an expression. Most JavaScript operators can be used for this purpose. Unary operators are probably safe, like ...
!function() {
// code
}();
... or...
void function() {
// code
}();
In both cases, it is function
considered as the only operand of the corresponding operator.
Both are functionally equivalent.
However, as a rule, many programmers prefer to open parentheses to indicate var - the result of a function, rather than the function itself.
The use of self-traversal functions is to pass in variables to store their "namespaces", such as common to pass in a window or document, or other things like jquery.
According to some quick tests on jslint, the preferred way to do this is the first (foo) in the following tests.
var foo = (function () {}());
var bar = (function () {})();
var baz = function () {}();
Note that invoking () are inside the outer parenthesis.
JSLint gives the following errors for bar and baz
Mistake:
Problem with line character 2: move the call to parens which contain the function.
var bar = (function (w) {}) (window);
Line character issue 3 27: Wrapping a direct function call in parentheses to help the reader understand that the expression is the result of a function, not the function itself.
var baz = function (w) {} (window);
source to share
As far as I know, this is just an agreement and is not absolutely necessary.
This is a good article on why this convention is useful:
http://peter.michaux.ca/articles/an-important-pair-of-parens
source to share