Javascript: In Javascript, what is Closure? Javascript tutorial
Closure has two features:
1. As a reference to a function variable-when a function is returned, it is activated.
2. A closure is a stack that does not release resources when a function returns.
Example 1.
FunctionsayHello2 (name ){
Vartext = 'hello' + name; // localvariable
VarsayAlert = function () {alert (text );}
Returnsaid;
}
Varsy = sayHello2 ('Never-online ');
Sy ();
Script
As a Javascript programmer, you should understand that the above Code is a reference to a function. If you still do not understand or do not know, please first understand some basic knowledge. I will not describe it here.
Why is the above Code a closure?
Because the sayHello2 function contains an embedded anonymous Function
SayAlert = function () {alert (text );}
In Javascript. If you create an embedded function (as shown in the preceding example), a closure is created.
In C or other mainstream languages, when a function returns, all local variables will be inaccessible because their stacks have been destroyed. However, if you declare an embedded function in Javascript, local variables are still accessible after the function returns. For example, the variable sy in the preceding example references the anonymous function () {alert (text) ;}in the embedded function. You can change the preceding example to the following:
FunctionsayHello2 (name ){
Vartext = 'hello' + name; // localvariable
VarsayAlert = function () {alert (text );}
Returnsaid;
}
Varsy = sayHello2 ('Never-online ');
Alert (sy. toString ());
Script
This is also consistent with the second feature of the closure.
Example 2.
Functionsay667 (){
// Localvariablethatendsupwithinclosure
Varnum= 666;
VarsayAlert = function () {alert (num );}
Num ++;
Returnsaid;
}
Varsy = say667 ();
Sy ();
Alert (sy. toString ());
Script
In the code above, the num in the anonymous Variable function () {alert (num);} is not copied, but continues to reference the value of the local variable defined by the external function-num, until the external function say667 () is returned.
[1] [2] [3] Next page