Home > Web Front-end > JS Tutorial > body text

JavaScript Closure Getting Started Example_Basic Knowledge

WBOY
Release: 2016-05-16 16:50:35
Original
1117 people have browsed it

1.

Copy code The code is as follows:

functionsay667(){
varnum=666;
varsayAlert=function(){alert(num);}
num ;
returnsayAlert;
}

varsayAlert=say667();
sayAlert();

2.

Copy code The code is as follows:

functionsetUpSomeGlobals(){
varnum=666;
gAlertNumber=function(){alert(num);}
gIncreaseNumber=function(){num ;}
gSetNumber=function(x){num=x;}
}

setUpSomeGlobals();//Assign values ​​to three global variables
gAlertNumber();//666
gIncreaseNumber();
gAlertNumber();//667
gSetNumber(12);
gAlertNumber();//12

3.

Copy code The code is as follows:

functionbuildList(list){
varresult=[];
for(vari=0;ivariiteml='item' list[i];
result.push(function(){alert( item '' list[i]);});
}
returnresult;
}

functiontestList(){
varfnlist=buildList([1,2,3]);
for(varj=0;jfnlist[j]() ;
}
}

4.

Copy code The code is as follows:

functionsayAlice(){
varsayAlert=function(){alert(alice);}
varalice='HelloAlice';
returnsayAlert;
}

varhelloAlice=sayAlice();
helloAlice();//HelloAlice

5.

Copy code 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);

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!