Home >Web Front-end >JS Tutorial >Closures in JavaScript_javascript tips
1. What is closure
Closure, the official explanation of 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.
Simply put, Javascript allows the use of internal functions---that is, function definitions and function expressions are located in the function body of another function. Furthermore, these inner functions have access to all local variables, parameters, and other inner functions declared in the outer function in which they exist. A closure is formed when one of these inner functions is called outside the outer function that contains them.
Characteristics of closures
1 function nested function
2 External parameters and variables can be referenced inside the function
3 Parameters and variables will not be recycled by the garbage collection mechanism
After the general function is executed, the local active object is destroyed, and only the global scope is saved in the memory. But the situation with closures is different!
function fn(){ var a = ; function fn(){ //可以访问fn中定义的a值 alert( a++ ); } fn(); } fn(); // fn(); // function fn(){ var a = ; function fn(){ //可以访问fn中定义的a值 alert( a++ ); } return fn;// } var f = fn(); f(); // 执行完后a还在内存中 f(); // f = null; //a被回收
The above is the editor’s introduction to closures in JavaScript. I hope it will be helpful to you!