Dr said:
JRS: ... Martin Honnen said:
(e-mail address removed) wrote:
[snip]
It is an expression statement that defines an anonymous function with a
function expression and then calls it directly.
What benefits does it have over just writing the body, apart from
enabling variables to be declared locally with no outside effect?
That's about the only reason to use an expression statement like that:
establish a new execution context, declare variables and functions
within it, but don't expose any of them to other code.
There are variations, such as:
var identifier = function() {
/* ... */
return /* ... */; /* An object or function reference,
* usually.
*/
}();
and:
(function() {
/* ... */
this.propertyName = /* ... */;
this.anotherProperty = /* ... */;
})();
but the aim is generally the same.
Are the opening parenthesis and its mate necessary?
Yes. Without the parentheses, the function token will be considered the
start of a function declaration, rather than a function expression:
expressions cannot start with either a function token, or an opening
brace (to avoid confusion with an object literal). Function declarations
must have an identifier, and as they do not evaluate to anything (they
are statements), the function object created by the declaration cannot
be called simply by appending a pair of parentheses. The latter would be
considered grouping parentheses missing the required, contained
expression. In short:
function() {
/* ... */
}();
is a twofold syntax error.
Mike