// 参数先给你存着,等你没参数了再一起给你
let currying = function (fn) {
let argArr = []
return function () {
if ( arguments.length === 0) {
// 卡了很久是因为不熟悉apply的参数列表跟fn的关系
// 虽然argArr是[1,2],但用apply的数组是参数列表,costTotal加参数只取第一个元素1
return fn.call(this, argArr)
} else {
Array.prototype.push.apply(argArr,arguments)
}
}
}
// 无参数时触发,使用之前存的参数
let costTotal = (function () {
let sum = 0
// 注意下面的匿名函数加不加参数取决于fn用的是call还是apply
return function (costDay) {
// apply用:for(let i=0;i<arguments.length;i++){,不传costDay
for(let i=0;i<costDay.length;i++){
sum += costDay[i]
console.log(`costDay${i+1}:`,costDay[i]);
}
console.log('sum',sum);
return sum
}
})()
let costCurrying = currying(costTotal)
costCurrying(10)
costCurrying(20)
costCurrying()
运行结果: