In javascript, what makes (...) exactly

Possible duplicate:
What do the parentheses associated with declaring a JavaScript object / object / class mean?

Talk to a colleague recently who is best

(function(){...}()) 

or

 (function(){...})() 

I was wondering what (...) actually does on a fundamental level, and what is the difference between what the js engine does in both cases. Is one approach theoretically (even if it is only small) faster than the other? If my function returns an object, what does (..) do for the object in the first example?

Can someone explain.

* edit The closest I got to an explanation on the Internet, http://dmitrysoshnikov.com/ecmascript/chapter-5-functions/#question-about-surrounding-parentheses , but this stops, in my opinion, explaining why the first The example above works in general.

+4
source share
2 answers

The first example works for the same reason as the second example. There is no real difference. This also works:

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

So does it:

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

The key is to position the function keyword in the statement at a point where the parser knows that this cannot be the start of a function declaration statement. In such cases, the function keyword should instantiate the function object as a value in the expression.

JavaScript statements other than expression expressions begin with keywords (for now, leave a note on the note). Inside any statement that does not start with the function keyword (going to a limb here), the only thing that function can mean is to create the value of the function object.

+2
source

You don't even need parentheses. The whole idea of ​​these parentheses is to make the function be expression , not a declaration. You can also achieve this as

 !function() { }(); 

This exclamation mark may also be + or - and some other characters. So it doesn’t matter if you use the “dog balls” option (your last) or not. In terms of performance, I can’t guarantee, but I'm 99.9% sure that there is zero difference (maybe it depends on the engine at best).

So, if we assume that there is no difference in performance between the two, this is an almost personal preference that you use. Crock has stated the second version many times as "dog balls" because you no longer wrap this expression. I would agree to that. As mentioned earlier, a template simply calls an expression of a function, and it must encapsulate it all for better readability.

+3
source

Source: https://habr.com/ru/post/1394635/


All Articles