Closure has two features:
1. As a reference to a function variable, the function is activated when it is returned.
2. A closure is a stack that does not release resources when a function returns.
Concept description (personal understanding is for reference only ):
When other functions are nested in a function, we can call them outer functions and nested functions. Embedded functions can access variables (local variables) defined in outer functions ). Assume that the nested function uses the variable of the outer function. If we use the embedded function as the return value of the outer function, we can use the outer function to obtain the reference of the embedded function. Then the closure is formed. After an external function is referenced by an embedded function through the outer function, the role of the outer function is completed. In traditional languages, local variables defined in the outer function are released, but not in Javascript closures! The nested function locks the local variables in the outer function until the external reference to the embedded function ends. The reason why the closure can be implemented is that JavaScript is interpreted and executed, and It scans the entireCodeAs long as embedded functions are used, the variables of the outer functions used by the embedded functions are not released until the embedded function reference ends. After talking about so many concepts, let's look at another example + perfect comments to understand everything!
<SCRIPT type = "text/JavaScript"> function fun1 () // fun1 is the outer function {var STR = "I love China"; return function () {alert (STR) ;}; // defines an anonymous embedded function (I am only anonymous for convenience). This anonymous function // uses the variable str of the outer function fun1, print Str. Pay attention to return. This anonymous function is the return value of fun1} var fun2 = fun1 (); // fun2 is the external function mentioned above ), here fun2 references the anonymous function alert in fun1 ("the execution of the outer function is complete! "); Fun2 (); // execute fun2, which is actually an embedded anonymous function. </SCRIPT>
The output in this example is: "The outer function has been executed !" "I love China ". It proves that the STR local variable in fun1 is not released.
Practical application:
Because I am also a beginner, I still don't know what the closure is .... I can't give examples of practical application, I can't study any more, and I will be scolded again... But there should be such a link to take up one place!