Pergunta

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.

Foi útil?

Solução

The first example works for exactly the same reason the second example works. There's no real difference. This also works:

!function() { ... } ();

So does this:

var _dont_care_ = function() { ... } ();

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, the function 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 that function can mean is the instantiation of a function object value.

Outras dicas

You don't even need parentheses at all. The whole idea of those parentheses is to force a function to be an expression and not a declaration. You can also achieve that like

!function() {
}();

That exclamationmark could also be + or - and some other characters. So, it makes no difference whether you are using the "dog balls" version (your latter one) or not. From a performance aspect, I can't guarantee but I'm 99.9% sure there is zero difference (maybe engine dependent variation at best).

So if we assume that there is no performance difference between those two, its pretty much personal preference which one you use. The Crock many times declared the second version as "dog balls" because you don't wrap the whole expression anymore. I'd agree on that. As mentioned before, the pattern does just force a function expression and it should encapsulate the whole thing for a better readability.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top