Call anonymous Javascript function

I read JS sources from Twitter - on my way to improve my JS knowledge base when I came across a strange way to call an anonymous function:

!function( $ ) { ... }( window.jQuery ); 

... and it works! :)

It is obvious to everyone that this:

 function ( $ ) { ... } ( window.jQuery ) 

not working (syntax error) while this is true:

 (function ( $ ) { .... })( window.jQuery ) 

Can someone explain this magic (why it works with !function )?

+47
javascript anonymous-function
Feb 01 2018-12-12T00:
source share
4 answers

When the function keyword is executed in the operator position (as the first token in the instruction), the function declaration is expressed as the function operator. Function statements rise to the top of the area, cannot be called immediately, and must have a name.

When a keyword occurs at the position of an expression (i.e., not like the first token in the expression, in your example ! β€”The first token), the function declaration is expressed as a function expression that can be anonymous and returns the value of the newly created function. Since it returns the value of the newly created function, you can immediately call it by adding brackets to it.

Wrapping a declaration inside parentheses does the same, but is more likely to be prefixed ! or + :

 (function () { ... }()); 
+66
Feb 01 2018-12-12T00:
source share

The second form of function () {} is a statement. The operator ! converts this to an expression. You will also find cases where people use - or + in front of the function keyword.

If you have an expression evaluating a function, you can call that function using the () operator.

Another (possibly simpler to understand) way to achieve the preservation effect is similar to another set of parentheses:

 ( function(x) { body; } )(arg); 

By placing the function inside the bracket, you again convert it to an expression that evaluates the function. This function is called with arg as an argument.

+7
Feb 01 '12 at 5:50
source share

As for the exclamation mark, this is not magic. It converts the result to true / false.

Your problem may be that your anonymous function has an error inside it.

0
Feb 01 2018-12-12T00:
source share

this sounds like a javascript syntax error:

a named function may be an operator, but an anonymous function simply treats it as an expression.

Pro: you can do function() { ... }()

Con: you cannot do function() { ... }

But why would people want to define an anonymous function without calling it? Thus, the conflict does not cause concern.

0
Jul 19 '12 at 7:44
source share



All Articles