Overview
Since the executive function is also called the call function immediately, as the name implies, can be executed immediately after the function declaration, we read the common JS library (such as jquery) source code, often found from the executive function of the figure, below my understanding. wording
There are two ways to do a self execution function:
The first one is more common:
(function () {
Console.log ("Method 1");
}) ();
The second type of writing is the JSLint recommendation, which looks more holistic:
(function () {
Console.log ("Method 2");
} ());
Both of these pieces of code are immediately output when executed. function
Self-executing functions appear to have two functions: the page load needs to do some setup work, such as initialization operations, these tasks do not need to repeat, so do not require a name of the reuse function to do these tasks sometimes need to use some variables, these variables can not pollute the global scope
The following example: We want to implement a function, when the user enters the page, give the user friendly hints, first, we think of declaring a method.
function ShowMessage () {
var message = ' Welcome ';
alert (message);
}
Later, we found that this method only need to execute once, so we remove the method, directly in the JS write:
var message = "Welcome";
alert (message);
At this point we found that if we wanted to declare another message in our future code, we would have to consider the problem of having a message in front of it, so we could write it as a function with the following code:
(function () {
var message = "Welcome";
alert (message);
}) ();
This is done only once and isolating the scope.