简体   繁体   English

我怎样才能让这个 javascript 函数调用自己?

[英]How can I get this javascript function to call itself?

As of right now my sum function looks like the code below.截至目前,我的 sum 函数类似于下面的代码。 It works and returns the sum of the consecutive calls.它工作并返回连续调用的总和。 But how can I make this work without the empty parenthesis at the end?但是我怎样才能在没有空括号的情况下完成这项工作呢? Like so theSum(5)(4)(3) which returns 12.就像返回 12 的theSum(5)(4)(3)

function theSum(x) {
    var total = x;

    function rec(y) {
        if (y === undefined) return total;
        total += y;
        return rec;
    };

    return rec;
}

console.log(theSum(5)(4)(3)()); // 12

Here is a suggestion utilizing a toString method:这是使用 toString 方法的建议:

function theSum(x) {
    var total = x;

    function rec(y) {
        total += y;
        return rec;
    };

    rec.toString = function() { return total; }

    return rec;
}

alert(theSum(5)(4)(3));

console.log(parseInt(theSum(5)(4)(3)));

Note however that you need to convert the returned reference to a string in some way so that you see the result.但是请注意,您需要以某种方式将返回的引用转换为字符串,以便您看到结果。

This is not possible.这不可能。 A function cannot return a function and an integer.函数不能返回函数和整数。 You can make theSum(5, 4, 3) = 12 or theSum([5, 4, 3]) = 12 .您可以使theSum(5, 4, 3) = 12theSum([5, 4, 3]) = 12

Closures and JavaScript duck typing to the rescue:闭包和 JavaScript 输入法来拯救:

function NumSumFun(initial){
    function NumSumNext(num) {
          initial+= num;
      return NumSumNext;
    }
    NumSumNext.valueOf = function () { return initial; }
    return NumSumNext;
}

var x = NumSumFun(10)(29); // ==> function 39
x + 1; // ==> 40

So whats happening.所以这是怎么回事。 It returns a function but the function has a valueOf property that has access to the accumulated value so the function acts as a number when used as a number.它返回一个函数,但该函数有一个 valueOf 属性,可以访问累积值,因此该函数在用作数字时充当数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM