People who have seen the jquery source should know that jquery begins with executing functions immediately. Immediate execution functions are commonly used in third-party libraries, with the benefit of isolating scopes, with a large number of variables and functions in any third-party library, and in order to avoid variable contamination (naming conflicts), the solution that developers think of is to use immediate execution functions.
1. What is the immediate execution function (Iife)
Make clear the form of function declarations, function expressions, and anonymous functions before you know to execute functions immediately, such as:
Next look at the two common forms of executing functions immediately: (function () {...}) () and (function () {...} ()), one is an anonymous function wrapped in a parenthesis operator, followed by a parenthesis, the other is an anonymous function followed by a parenthesis, and then the entire package in a parenthesis operator, both of which are equivalent. To immediately execute the function can be done immediately, pay attention to two points, one is the function body after the parentheses (), and the second is that the function body must be a function expression and not a function declaration. Look first:
As you can see, in addition to using the () operator,! , +,-,= and other operators can play a role of immediate execution. The function of these operators is to convert an anonymous function or function declaration to a function expression, as shown, the function body is the form of a function declaration, and the operator converts it to a function expression to achieve immediate effect:
2. Benefits of using the immediate execution function
By defining an anonymous function, a new function scope is created, which is equivalent to creating a "private" namespace, and the variables and methods of that namespace do not break the polluting global namespace. at this point, if you want to access the global object, the global object is passed in as a parameter , such as the jquery code structure:
Where window is the global object. Scope isolation is important, a feature that the JS framework must support, and jquery is used in thousands of JavaScript programs, and you must ensure that the variables created by jquery do not conflict with the variables used to import his program.
(turn) The immediate execution function of the literacy--javascript