Explanation of closures
An expression (usually a function) that has many variables and an environment in which these variables are bound, and therefore these variables are also part of the expression. A closure is a function that has the right to access a variable of another function scope
In JavaScript, only a child function inside a function can read a local variable, so a closure can be simply understood as " a function defined inside a function ". So, in essence, closures are bridges that connect functions inside and outside of functions.
Features of closures:
1) as a reference to a function variable, when the function returns, it is in the active state.
2) A closure is when a function returns, a stack that does not release resources.
Simply put, JavaScript allows the use of intrinsic functions---that is, function definitions and function expressions in the function body of another function. Furthermore, these intrinsic functions can access all local variables, arguments, and other intrinsics declared in the outer function in which they are located. When one of these intrinsics is called outside the outer function that contains them, a closure is formed.
Closures Application Scenario
1.setTimeout
setTimeout(func,time)
Func here can not take parameters, to solve this problem need to use closures
function func (param) { returnfunction() { alert (param);} } var f = func (11000);
2. Replace global variables
// closure, Test2 is a local variable, which is the purpose of the closure // We often use global variables in small scopes, which can be replaced by closures. (function () { var test2=222; function outer () {alert (test2);} function Test () {alert ( "test closure:" +test2);} Outer (); // 222 test (); // test closure: 222 }) (); alert (test2); // Undefined, there is no access to test2
3. Loop-Bind the click event for the node, using the value or node of the secondary loop in the event function, instead of the last loop value or node
4. Create a privileged method for access control
Note points for using closures
(1) Because the closure will make the variables in the function are stored in memory, memory consumption is very large, so can not abuse closures, otherwise it will cause the performance of the Web page, in IE may cause memory leaks. The workaround is to remove all unused local variables before exiting the function.
(2) The closure will change the value of the inner variable of the parent function outside the parent function. So, if you use the parent function as an object, and the closure as its public method, and the internal variable as its private property (private value), be careful not to arbitrarily change the value of the inner variable of the parent function.
Application scenario of JS closure package