Closure: Special grammatical phenomena of local variables can also be used outside the function
Global variables VS Local variables:
Global variables: Benefits: shareable, reusable;
Cons: Can be arbitrarily modified at any location-global pollution
Local Variables: Benefits: Security
Cons: Not shareable, non-reusable
When to use closures: that is, share local variables, and do not want to tamper with random.
Ii. Building a closure structure: 3 steps:
1. Encapsulating protected local variables using the outer function
2. Inside the outer function, define the inner function that specifically operates the local variable * and return *.
3. In the global call to the outer function, get the inner function of the object, saved in the global variable used repeatedly.
Three, closure three characteristics:
1. Nesting functions
2. The inner function uses the local variables of the outer function
3. The inner function object is returned to the outside, and is called repeatedly at the global level
Iv. the role of closures: protecting shareable local variables
* How to quickly determine the output of the closure function: *
1. The outer function was called several times and there were several protected local variables
Five, classic questions
1.
Function F1 () {
var n=999;
Nadd=function () {n+=1}
function F2 () {alert (n);}
return F2;
}
var result=f1 ();
Result ();
Nadd ();
Result ();
2.
function Fun1 () {
var arr=[];
for (var i=0;; i<3;i++) {
Arr[i]=function () {return i};
}
I=3
return arr;
/*
function () {return i}
function () {return i}
function () {return i}
*/
}
var arr=fun1 (); Closure one Create i=3
Console.log (Arr[0] ()); 3
Console.log (Arr[1] ()); 3
Console.log (Arr[2] ()); 3
3.
var Getsecret,setsecret;
(function () {
var secret=0;
Getsecret=function () {
Return secret;
}
Setsecret=function (sec) {//var function Setsecret (sec) {}
Secret=sec;
}
})();
window.secret=100;
Console.log (Getsecret ()); 0
Setsecret (55);
Console.log (Getsecret ()); 55
The closure problem in JS