js
var foo = function(...args) // 要求实现函数体}
var f1 = foo(1,2,3); f1.getValue(); // 6 输出是参数的和
var f2 = foo(1)(2,3); f2.getValue(); // 6
var f3 = foo(1)(2)(3)(4); f3.getValue(); // 10解法1:拓展Function对象,函数调用自己
js
Function.prototype.getValue = function(){
let num = this.arr.reduce((x,y)=>x+y)
this.arr = null // 清除
return num
}
// 调用foo的时候,会从Function中继承arr的属性
function foo(...args){
if(!Array.isArray(foo.arr)){
foo.arr = []
}
foo.arr.push(...args)
return foo
}解法2:直接拓展函数自身,避免出现拓展Function的情况
js
function foo(...args){
let num = (..._args)=> foo(...[...args,..._args])
target.getValue = num.reduce((x,y)=>x+y)
return target
}