函数柯里化(就是一个函数)是把接受多个参数的函数转变成接受一个单一参数(最初函数的第一个参数),并且返回接受余下的参数而且返回结果的新函数的技术。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
function add(a, b, c, d) {
return a + b + c + d;
}
// 打印输出61
console.log(add(10, 20, 30, 1));
// 柯里化的功能函数
function FixedCurry(fn) {
var _arg = Array.prototype.slice.call(arguments, 1);
return function() {
// arguments[5, 6]
var newArg = _arg.concat([].slice.call(arguments, 0));
return fn.apply(this, newArg);
}
}
// 返回一个新的函数,这个函数就是经过柯里化处理以后的函数
// 如果参数传递完成,会执行,没有传递完成,会继续返回一个函数,期待下次调用的时候传递完成,传递完成执行函数
// var newAdd = Curry(add,10,20);
// console.log(newAdd(5,6));
function Curry(fn, length) {
// fn.length获取函数形参的个数
var length = length || fn.length;
return function() {
if (arguments.length < length) {
// 参数没有传递完成
var num = [fn].concat( [].slice.call(arguments, 0) );
return Curry(FixedCurry.apply(this,num), length = arguments.length - 1);
} else {
// 参数传递完成
return fn.apply(this, arguments);
}
}
}
var newAdd = Curry(add);
// 打印输出100
console.log(newAdd(10, 20, 30, 40));
</script>
</body>
</html>