Closures are functions that have access to variables in another function scope, and the most common way to create closures is to create another function within one function, access the local variables of the function through another function, and use closures to break through the scope of the action and pass the variables and methods inside the function to the outside.
characteristics of closures:
1. Nested functions within functions
2. Intrinsic functions can refer to the outer parameters and variables
3. Parameters and variables are not recycled by the garbage collection mechanism
Html:
<!--The onclick event of the Li node will correctly eject the currently clicked Li Index.
<ulID= "Testul"> <Li>index = 0</Li> <Li>index = 1</Li> <Li>index = 2</Li> <Li>index = 3</Li></ul>
Js:
<script type= "Text/javascript" > var nodes = document.getelementsbytagname ("li"); for (i = 0;i<nodes.length;i+= 1= (function(i) { return function// without closure, the value is 4} each time ) (i); }</script>
Then we look at the following piece of code, which is a very straightforward description of the closure function:
function say667 () {// Local variable that ends up within closurevar num = 666; varfunction() {alert (num); } num+ +; return Sayalert;} var sayalert = say667 (); Sayalert ()// execution Results should pop up 667
After executing say667 (), the say667 () closure internal variable will exist, and the inner variable of the inner function of the closure will not exist
Make JavaScript garbage collection mechanism GC does not reclaim resources occupied by say667 ()
Because the execution of the intrinsic function of say667 () relies on the variables in the say667 ()
What is a closure (closure) and why use it?