The so-called closure is an expression (usually a function) that has many variables and an environment bound to these variables, so these variables are also part of the expression.
My understanding here is: In fact, all function methods in js can actually be counted as closures. In simple terms, they can also be understood as nested functions. Usage of the method:
For example, the following code example:
function run(){ var a=10; return function(){ a++; console.log(a); } } var foo=run(); foo();//11 foo();//12 foo();//13
Analysis: The value of foo at this time is equal to run( ) The return value of the function, the foo function is a closure;
1) The execution process is to first call the foo() method. The foo() method will find the return function method in the run() method. This The return function method will point to the a variable in the run() method, and then when foo() is executed, 11 will be output;
2) In the above example, due to the existence of the closure, the function After run returns, a in run() always exists, so that every time foo() is executed, a will be the value of a after adding 1 to the console.
Related recommendations:
The most detailed explanation of closures
##In-depth understanding of js closures
The above is the detailed content of Detailed explanation of how Javascript closures work. For more information, please follow other related articles on the PHP Chinese website!