The code copy is as follows:
var add = function(a){
return function(b){
return function(c){
return a+b+c;
};
};
};
add(1)(2)(3); //6
That's right! If there are 4 calls like add(1)(2)(3)(4), then this will definitely not apply.
This is similar to executing a function to return the function's own value:
The code copy is as follows:
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
However, after the calculation is completed, the function tmp is returned, so that the result of the calculation cannot be obtained. The result we need is a calculated number. So what should we do? First of all, we need to know that in JavaScript, printing and adding calculations will call the toString or valueOf functions respectively, so we rewrite tmp's toString and valueOf methods to return the value of sum;
The above is all about this article, I hope you like it.