1 function sub_curry(fn) { 2 var args = [].slice.call(arguments, 1); 3 return function() { 4 return fn.apply(this, args.concat([].slice.call(arguments))); 5 }; 6 } 7 8 function curry(fn, length) { 9 length = length || fn.length; 10 return function() { 11 if (arguments.length < length) { 12 var combined = [fn].concat(Array.prototype.slice.call(arguments)); 13 return curry(sub_curry.apply(this, combined), length - arguments.length); 14 } else { 15 return fn.apply(this, arguments); 16 } 17 }; 18 } 19 20 function add(a, b, c) { 21 console.log(a + b + c); 22 } 23 24 curry(add)(1, 2, 3); 25 curry(add)(1, 2)(3); 26 curry(add)(1)(2, 3); 27 curry(add)(1)(2)(3);
注:
(1)arguments是调用函数时传入的入参;
(2)[].slice.call(arguments)同 Array.prototype.slice.call(arguments); 作用是把arguments转化为数组格式。
(3)fn.length可以拿到函数的入参的长度
简易版本:
1 function add() { 2 var args = Array.prototype.slice.call(arguments); 3 var sub_add = function() { 4 args.push(...arguments); 5 // var chilsArgs = Array.prototype.slice.call(arguments); 6 // args = args.concat(chilsArgs); 7 return sub_add; 8 } 9 sub_add.toString = function() { 10 return args.reduce((acc, val) => acc + val) 11 } 12 return sub_add; 13 } 14 15 add(1,2,3); //6 16 add(1,2)(3); //6 17 add(1)(2)(3); //6