Possible Duplicate:
What do parentheses surrounding a JavaScript object/function/class declaration mean?
Recently discussing with a colleague which is best
(function(){...}())
or
(function(){...})()
I got to wondering what ( ... ) actually does at a fundamental level, and what is the difference between what the js engine does in both the above cases. Is one approach theoretically (even if only a tiny amount) faster than the other? If my function returns an object what does ( .. ) do to the object in the first example?
Can anyone explain.
*edit The closest I've got to an explanation on the internet is http://dmitrysoshnikov.com/ecmascript/chapter-5-functions/#question-about-surrounding-parentheses, but this stops short, in my view, of explaining why the first example above works at all.
The first example works for exactly the same reason the second example works. There's no real difference. This also works:
So does this:
The key is to arrange for the
function
keyword to appear in the statement at a point where the parser knows that it cannot be the start of a function declaration statement. In such cases, thefunction
keyword must be instantiating a function object as a value in an expression.Statements in JavaScript other than expression statements start with keywords (leave labels aside for the moment). Inside any statement that doesn't start with the
function
keyword (going out on a limb here), the only thing thatfunction
can mean is the instantiation of a function object value.