问题
I want to make a function which adds arguments. Invoking this function should be
functionAdd(2)(3)(4)...(n);
And the result 2+3+4...+n I'm trying this
function myfunction(num){
var summ =+ num;
if(num !== undefined){
return myfunction(summ);
}
};
But it doesn't works, an error of ovwerflow. And I don't understand where I should out from this function;
回答1:
You can use the .valueOf
to do the trick:
function myfunction(sum){
var accum = function(val) {
sum += val;
return accum;
};
accum.valueOf = function() {
return sum;
};
return accum(0);
};
var total = myfunction(1)(2)(3)(4);
console.log(total); // 10
JSFiddle: http://jsfiddle.net/vdkwhxrL/
How it works:
on every iteration you return a reference to the accumulator function. But when you request for the result - the .valueOf() is invoked, that returns a scalar value instead.
Note that the result is still a function. Most importantly that means it is not copied on assignment:
var copy = total
var trueCopy = +total // explicit conversion to number
console.log(copy) // 10 ; so far so good
console.log(typeof copy) // function
console.log(trueCopy) // 10
console.log(typeof trueCopy) // number
console.log(total(5)) // 15
console.log(copy) // 15 too!
console.log(trueCopy) // 10
回答2:
If last call can be without arguments:
function add(value) {
var sum = value;
return function add(value) {
if(typeof value === 'number') {
sum += value
return add
} else {
return sum
}
}
}
console.log(add(1)(2)(3)(0)()) // 6
来源:https://stackoverflow.com/questions/29376702/tail-function-in-javascript