What is the name / purpose of the template?

I did not find a message asking for a template like this, sorry if I missed it.

Anyway, I repeat this pattern in many jQuery plugins or scripts:

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

What is his purpose? Does he have a name?

Thanks!

+6
source share
4 answers

It is also known as an Expression Exited Function Expression expression.

Ben Alman is a good article on the use of IIFE , and why the “self- executing anonymous function” is not the best terminology:

One of the most beneficial side effects of an immediate call. Function expressions are that because it is unnamed or anonymous, the function expression is called immediately, without using an identifier, a closure can be used without polluting the current area.

[... T] the term "self-fulfillment" is somewhat misleading, since it is not a function that performs itself, although the function is performed. In addition, “anonymous” is unnecessarily specific because the Expression “Called Function” can immediately be anonymous or by name. As for my preference, “called out” over “fulfilled,” then his simple question is alliteration; I think IIFE looks and sounds better than IEFE.

+5
source

This is an expression with an immediate call expression.
This is useful for creating an area for its contents. It looks like this:

 function myFunc() { //code } myFunc(); 

But there are 2 differences:

  • Function called here
  • The above code is a function declaration other than a function expression. "myFunc" above is stored as a variable unless you use it as an expression, for example:

     foo(function myFunc() { //code }); 

Then it will not be saved as a variable.

+3
source

This is a function call ( Fiddle ) immediately called:

 (function () { alert("pee"); }()); 
+3
source

This is an instantly called function - as soon as you declare it, it calls the call.

The syntax () in Javascript means “call this function with any arguments between ( and ) . Since there is nothing between the brackets in your example, the arguments to the function are not passed; but if you need to specify arguments, you can do something like this:

 (function foo(arg1, arg2) { alert(arg1 + " " + arg2); })(3, 5); 

which will immediately call foo() and go into 3 and 5 as two arguments.

+1
source

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


All Articles