javascript中的尾部函数 [英] Tail function in javascript
问题描述
我想创建一个添加参数的函数。调用此函数应为
I want to make a function which adds arguments. Invoking this function should be
functionAdd(2)(3)(4)...(n);
结果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);
}
};
但它不起作用,是ovwerflow的错误。而且我不明白我应该从这个函数出来的地方;
But it doesn't works, an error of ovwerflow. And I don't understand where I should out from this function;
推荐答案
你可以使用。 valueOf
要做的诀窍:
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/
JSFiddle: http://jsfiddle.net/vdkwhxrL/
工作原理:
在每次迭代时返回对累加器函数的引用。但是当您请求结果时 - <$调用c $ c> .valueOf() ,改为返回标量值。
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
这篇关于javascript中的尾部函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!