DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> JavaScript基礎知識 >> javascript閉包入門示例
javascript閉包入門示例
編輯:JavaScript基礎知識     

1.
復制代碼 代碼如下:
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<list.length;i++){
variteml='item'+list[i];
result.push(function(){alert(item+''+list[i]);});
}
returnresult;
}

functiontestList(){
varfnlist=buildList([1,2,3]);
for(varj=0;j<fnlist.length;j++){
fnlist[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);

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved