Home > Article > Web Front-end > What is js closure
A closure is a function that can read the internal variables of other functions. Since in JavaScript, only subfunctions inside a function can read local variables, closures can be understood as "functions defined inside a function." In essence, closures are a bridge between the inside of a function and the outside of the function.
JavaScript Closure
Allows function definitions and function expressions in JavaScript to be located within the function body of another function (internally function), and inner functions can access all local variables, parameters, and other inner functions in the declaration of the outer function in which they are located. When one of the internal functions is called outside the external function, a closure will be formed.
The three major characteristics of closures are:
1. Function nested functions
2. Internal functions can access variables of external functions.
3. Parameters and variables will not be recycled.
Uses of closures
Closures can be used in many places. It has two greatest uses. One is to read the variables inside the function as mentioned earlier, and the other is to keep the values of these variables in memory.
Notes on using closures
1) Since closures will cause the variables in the function to be stored in memory, the memory consumption is very large, so they cannot be abused. Closure, otherwise it will cause performance problems on the web page and may cause memory leaks in IE. The solution is to delete all unused local variables before exiting the function.
2) The closure will change the value of the variable inside the parent function outside the parent function. Therefore, if you use the parent function as an object, the closure as its public method, and the internal variables as its private value, you must be careful not to Feel free to change the value of the variable inside the parent function.
Summary:
1. A closure refers to a function that has access to variables in the scope of another function. The most common way to create a closure is to Create another function within a function and access the local variables of this function through another function. The disadvantage of closures is that they are resident in memory, which increases memory usage. Improper use can easily cause memory leaks.
2. Don’t worry about what counts as a closure. In fact, every function you write counts as a closure. Even if it is a global function, when you access global variables outside the function, it is a manifestation of closure.
The above is the detailed content of What is js closure. For more information, please follow other related articles on the PHP Chinese website!