1.概念
一个函数可以接受多个参数,反复被调用,例fn(1,2,3,4,5)(6,7)(8,9,10)
,该技术被命名为函数柯里化。
2.示例
需求:求和fn(1,2,3,4,5)(6,7)(8,9,10)
代码:
function currying() { //12345
// arguments 伪数组 ,具备数组的属性,但是不包含数组的方法
const args = Array.prototype.slice.call(arguments);
// const args = []._proto_.slice.call(arguments);
// Array.prototype.slice 是原型上的一个方法
// call 改变this指向
// 数组方法依赖于内部是this数据容器来执行
// console.log(args);
// 一个函数访问外部变量,形成闭包
const inner = function () { //67 8910
// args
args.push(...arguments)
return inner
}
// inner函数toString改不了,改一个计算原始数据类型的方式
inner.__proto__[Symbol.toPrimitive]= inner.toString=inner.getValue = function () {
return args.reduce((num1, num2) => {
return num1 + num2
}, 0)
}
return inner;
}
let res = currying(1, 2, 3, 4, 5)(6, 7)(8, 9, 10)
// let sum = res.getValue()
// console.log(sum);
// 可以允许将返回值二次计算
console.log(res-1);