This article mainly introduces several examples of javascript closures and understands these examples. For closures, it should be an entry. If you need them, refer to section 1.
The Code is as follows:
Functionsay667 (){
Varnum= 666;
VarsayAlert = function () {alert (num );}
Num ++;
Returnsaid;
}
VarsayAlert = say667 ();
SayAlert ();
2.
The Code is as follows:
FunctionsetUpSomeGlobals (){
Varnum= 666;
Required tnumber = function () {alert (num );}
GIncreaseNumber = function () {num ++ ;}
GSetNumber = function (x) {num = x ;}
}
SetUpSomeGlobals (); // assign values to three global variables
Required tnumber (); // 666
GIncreaseNumber ();
Required tnumber (); // 667
GSetNumber (12 );
Required tnumber (); // 12
3.
The Code is as follows:
FunctionbuildList (list ){
Varresult = [];
For (vari = 0; I Variteml = 'item' + list [I];
Result. push (function () {alert (item + ''+ list [I]);});
}
Returnresult;
}
FunctiontestList (){
Varfnlist = buildList ([1, 2, 3]);
For (varj = 0; j Fnlist [j] ();
}
}
4.
The Code is as follows:
FunctionsayAlice (){
VarsayAlert = function () {alert (alice );}
Varalice = 'helloalice ';
Returnsaid;
}
VarhelloAlice = sayAlice ();
HelloAlice (); // HelloAlice
5.
The Code is as follows:
FunctionnewClosure (someNum, someRef ){
Varnum = someNum;
VaranArray = [1, 2, 3];
Varref = someRef;
Returnfunction (x ){
Num + = x;
AnArray. push (num );
Alert ('num: '+ num +' \ nanArray '+ anArray. toString () +' \ nref. someVar '+ ref. someVar );
}
}
Closure1 = newClosure (40, {someVar: 'closure1 '});
Closure2 = newClosure (1000, {someVar: 'closure2 '});
Closure1 (5 );
Closure2 (-10 );