# Functional Programming - Closure & Curry Note Closures: 模組模式可經由建立一個模組實體來調用內層函式,而內層函式由於具有閉包的特性,因此可存取外層的變數和函式。透過模組模式,可隱藏私密資訊,並選擇對外公開的 API (Backend??)。 Closure Factor: ``` function makeAdder(x) { return function(y) { return x + y; }; } var add5 = makeAdder(5); var add10 = makeAdder(10); console.log(add5(2)); // 7 console.log(add10(2)); // 12 ``` > add5 與 add10 都是 closure。他們共享函式的定義,卻保有不同的環境:在 add5 的作用域環境,x 是 5。而在 add10 的作用域環境, x 則是 10。 ---- Curry function: ``` function add(x) { return function(y) { if (typeof y !== 'undefined') { x = x + y; return arguments.callee; } else { return x; } }; } add(1)(2)(3)(); //6 add(1)(1)(1)(1)(1)(1)(); //6 ``` > 更易於在非同步狀態下使用 note: arguments.callee removed from ES5 strict mode https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee Reference: > https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Closures https://cythilya.github.io/2018/10/22/closure/