Skip to content

Instantly share code, notes, and snippets.

@iansrc0811
Last active March 9, 2017 09:21
Show Gist options
  • Save iansrc0811/0a4660af46d3ff6ab912405d11c52b1e to your computer and use it in GitHub Desktop.
Save iansrc0811/0a4660af46d3ff6ab912405d11c52b1e to your computer and use it in GitHub Desktop.
簡單的closure範例
//可以把 閉包( closure) 想成是在函式執行完畢後,
//讓你「記住」並持續存取一個函式 scope (範疇) 的變數 的一種方式
function makeAdder(x) {
function add(y){
return y + x;
}
return add;
}
var plusOne = makeAdder(1);
// plusOne 取得到內層函數 add() 的參考, 並帶有一個closure包含了外層 makeAdder() 的參數'x'
var plusTen = makeAdder(10);
//同plusOne
plusOne(3); // 4 --> 3+1
plusOne(41); // 42 --> 41+1
plusTen(14); // 24 --> 14+10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment