Home >Web Front-end >JS Tutorial >js method to execute function immediately
Those who have read the jQuery source code should know that jQuery uses an immediate execution function at the beginning. Immediate execution functions are often used in third-party libraries. The advantage lies in the isolation scope. Any third-party library will have a large number of variables and functions. In order to avoid variable pollution (naming conflicts), the solution developers come up with is to use immediate execution functions.
1. What is an immediate execution function (IIFE)
Before understanding the immediate execution function, first clarify the form of function declaration, function expression and anonymous function, as shown below:
Let’s look at two common forms of immediate execution of functions: (function(){…})() and (function (){…} ()), one is An anonymous function wrapped in a parentheses operator, followed by a parentheses, and an anonymous function followed by a parentheses, and then wrapped entirely in a parentheses operator, are equivalent. If you want to execute a function immediately, you must pay attention to two points. First, there must be parentheses () after the function body. Second, the function body must be a function expression rather than a function declaration. First look at the picture below:
#As can be seen from the picture, in addition to using the () operator,! , +, -, = and other operators can all be executed immediately. The function of these operators is to convert anonymous functions or function declarations into function expressions. As shown in the figure below, the function body is the form of a function declaration. After using operators to convert it into a function expression, the immediate execution effect can be achieved:
2. Benefits of using immediate execution functions
By defining an anonymous function, a new function scope is created, which is equivalent to creating a "private function". "namespace, the variables and methods of this namespace will not destroy and pollute the global namespace. If you want to access the global object at this time, just pass the global object in the form of parameters, such as jQuery code structure:
where window is the global object. Scope isolation is very important and is a feature that a JS framework must support. jQuery is used in thousands of JavaScript programs. It must be ensured that the variables created by jQuery cannot conflict with the variables used by the program that imports it.
Related recommendations:
Detailed explanation of js immediate execution function instance
Detailed explanation of immediate execution function instance in JavaScript
Detailed explanation of JavaScript anonymous, named functions and immediate execution functions IIFE
The above is the detailed content of js method to execute function immediately. For more information, please follow other related articles on the PHP Chinese website!