首先實現柯里化函數es6
function curry(fn) { const len = fn.length; return function curred(...args) { if (args.length >= len) { return fn(...args); } else { return curred.bind(null, ...args); } }; }
調用函數
function show(a = 0, b, c) { console.info(a, b, c); } const next = curry(show); next("g")("ccc")("ooo");
輸出:spa
爲何會這樣?
去掉參數a的默認值就行了,查閱函數的擴展 ### 函數的 length 屬性作了詳細的說明:第一個參數a設置了默認值致使show.length爲0,(也就是說默認值致使函數參數的長度變小了)這樣傳遞一個參數"g"調用執行了show,show執行完返回的是undefined因此後面再調用next就報錯了。因此對須要柯里化的函數儘可能不要傳遞默認值。code