可以把 function 當作變數來傳
以下是一個函式工廠的簡單範例:
var add10 = function(i){
return function(){
return 10 + i;
};
}
//利用add10造出getEleven這個function
var getEleven = add10(1);
alert(getEleven());
Why functional style?
- No more outer variables(side effect)
- describles "What to get" not "How to get"
Arrow function(EM6 for all browser)
var sqaure = function (n){
}
可以簡化成
var sqaure = n => {return n * n}
再簡化成
var sqaure = n => n * n; //better
Closure
a function factory generates closure
A function with environment (保存執行的當下環境,像工廠產生出來的function)
var functionFactory = function (n){
}
functionFactory根據Arrow function 可以改寫成:
var functionFactory = n => m=> m + n;
var addOne = functionFactory(1);
var two = addOne(1); // m => m+1
var addTen = functionFactory(10);
var eleven = addTen(1); //m => m+ 10
addOne and addTen are closures
setTimeout problem
for(var i=1; i<3; i++){
- setTimeout(function() { console.log(i)}, 1000 * i);
}
why 3 3 , not 1 2 ?
Filter
[2, 3, 4, 5].filter( n=> n<4);
Reduce
[80, 90, 92, 76].reduce((prev, curr) => prev + curr);
reduce 意義: var reduceFunction = (reduced, currentVal) => ......
Sort
(a, b) < 0 then the order becomes (a, b)
(a, b) = 0 then nothing happened
(a, b) > 0 then the order becomes (b, a)
var compareFunction = (a, b) => (a % 2) - (b % 2)
[1, 2, 3, 4, 5, 6,7,8].sort(compareFunction) becomes [2,4,6,8,1,3,5,7]