[JavaScript]Closure
Posted In:
Javascript
.
By 卡西卡
Closure:閉包, 閉鎖空間, 封絕
- 看起來有點像是“巨集”的,可以產生(return)新的函式。
// 打折
function Discount(percent) {
return function(price) { return price * percent / 100.0; }
}
var VIP_Pay = Discount(60); // 貴賓6 折
var Member_Pay = Discount(80); // 會員8 折
var Consumer_Pay = Discount(95); // 門市95折
var dvd_price = 500;
print("DVD定價 "+dvd_price);
print("貴賓特惠價 "+VIP_Pay(dvd_price));
print("會員優待價 "+Member_Pay(dvd_price));
print("門市售價 "+Consumer_Pay(dvd_price));
/* 結果
DVD定價 500
貴賓特惠價 300
會員優待價 400
門市售價 475
*/
- 從石頭閒語搬來的程式片斷
var i = 0;
var funcSet = [];
function run_funcSet() {
for (var j=0, func=funcSet[j] ; func ; func=funcSet[++j] ) {
func();
} // for
}
print('Pure anonymous function');
for ( i=0 ; i<3 ; i++ ) {
funcSet[i] = function() {print(i);}
} // for
run_funcSet();
print('Closure');
for ( i=0 ; i<3 ; i++ ) {
funcSet[i] = (
function(i) {
return function(){print(i);}
} // function
)(i);
} // for
run_funcSet();
/* 結果
Pure anonymous function
3
3
3
Closure
0
1
2
*/
參考資料:
0 Responses to [JavaScript]Closure
Something to say?