js implements methods similar to the way add of 1 of 2 of 3 calls

  • 2020-05-10 17:42:53
  • OfStack


var add = function(a){
    return function(b){
        return function(c){
            return a+b+c;
        };
    };
};
add(1)(2)(3); //6

That's right! And if you have four calls to add of 1, 2, 3, and 4, then this is definitely not going to work.

This is similar to executing a function and returning the value of the function itself:


function add(x) {
    var sum = x;
    var tmp = function (y) {
        sum = sum + y;
        return tmp;
    };
    tmp.toString = function () {
        return sum;
    };
    return tmp;
}
console.log(add(1)(2)(3));  //6
console.log(add(1)(2)(3)(4));   //10

After completion of the calculation but returned to their tmp the function, thus obtain the calculation results, we need is the result of a calculation of the number so what can we do, the first thing to know JavaScript, print and add calculation, will call toString or valueOf function respectively, so we rewrite tmp toString and valueOf method, return the value of sum;

That's all for this article, I hope you enjoy it.


Related articles: