javascript闭包入门示例_基础知识
程序员文章站
2022-05-29 11:29:55
...
1.
functionsay667(){
varnum=666;
varsayAlert=function(){alert(num);}
num++;
returnsayAlert;
}
functionsetUpSomeGlobals(){
varnum=666;
gAlertNumber=function(){alert(num);}
gIncreaseNumber=function(){num++;}
gSetNumber=function(x){num=x;}
}
functionbuildList(list){
varresult=[];
for(vari=0;ivariteml='item'+list[i];
result.push(function(){alert(item+''+list[i]);});
}
returnresult;
}
functionsayAlice(){
varsayAlert=function(){alert(alice);}
varalice='HelloAlice';
returnsayAlert;
}
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);
}
}
复制代码 代码如下:
functionsay667(){
varnum=666;
varsayAlert=function(){alert(num);}
num++;
returnsayAlert;
}
varsayAlert=say667();
sayAlert();
2.
复制代码 代码如下:
functionsetUpSomeGlobals(){
varnum=666;
gAlertNumber=function(){alert(num);}
gIncreaseNumber=function(){num++;}
gSetNumber=function(x){num=x;}
}
setUpSomeGlobals();//为三个全局变量赋值
gAlertNumber();//666
gIncreaseNumber();
gAlertNumber();//667
gSetNumber(12);
gAlertNumber();//12
3.
复制代码 代码如下:
functionbuildList(list){
varresult=[];
for(vari=0;i
result.push(function(){alert(item+''+list[i]);});
}
returnresult;
}
functiontestList(){
varfnlist=buildList([1,2,3]);
for(varj=0;j
}
}
4.
复制代码 代码如下:
functionsayAlice(){
varsayAlert=function(){alert(alice);}
varalice='HelloAlice';
returnsayAlert;
}
varhelloAlice=sayAlice();
helloAlice();//HelloAlice
5.
复制代码 代码如下:
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);