Javascript functions run automatically only when called

I am working on some code in which this page has many .js files associated with it (using them as libraries). Each .js file looks like this:

(function() { .... all the lib functions and objects .... })(); 

After some playback, I see that the format functions (function () {...}) (); obtained automatically. If I separate the outer finger from the function () {...} , then the code is invalid. If I add a function name, then the code will be valid, but will not be executed until the function foo () {...} is called.

Is there a special reason why lib was written this way? I would suggest that it will encapsulate variable names, etc. What is the syntax of this that allows it to run automatically when the page loads?

+4
source share
3 answers

This is called IIFE, Expression with immediate calling function .

It allows you to define variables, including functions that are not visible from the outside and do not burden the global namespace.

 (function() { var v = ... // this variable can be used in the IIFE but not from outside })(); 

The reason you need an outer bracket is because the expression starting with function something is interpreted as declaring a function, which would be incorrect here because the declaration function requires a name . You must use the trick to make it an expression. Parenthesis do this, but you could use other tricks like

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

but the outer bracket is the clearest and probably less surprising solution.

+5
source

Most libraries have anonymous functions without a name.

Therefore, it will need to be done immediately. Because you cannot call a function later that does not have a name and should be called immediately.

+1
source

What is the syntax of this, which allows it to start automatically when the page loads

It is not called when the page loads, it is called immediately after the declaration. And this is because parentheses are included:

 })(); ^^ 

If I separate the outer finger from function() {...} , then the code is invalid.

What the well-known syntax of JavaScript syntax is: it must be considered as an expression of a function in order to be able to immediately call; otherwise, it is interpreted as a function declaration that cannot be called immediately.

Is there a special reason why lib was written this way? I would suggest that it will encapsulate variable names, etc.

Yes, most likely the global namespace is clean.

+1
source

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


All Articles