原生JS实现add(1)(2)(3)(4)的调用方式

method 1:

var add = function (m) {
 
    var temp = function (n) {
        return add(m + n);
    }
 
    temp.toString = function () {
        return m;
    }
 
    return temp;
};
 
 
add(3)(4)(5); // 12
add(3)(6)(9)(25); // 43

method 2:

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

牛逼了,考查递归调用或者闭包,js基础功能

利用函数的柯里化也是可以实现的,参考柯里化小结

method 3:利用了函数的柯里化和闭包特性

 1 function add(...arg) {
 2   var a = [...arg];
 3   _add = function (...innerArg) {
 4     if (innerArg.length === 0) {
 5       return a.reduce(function (a, b) { return a + b })
 6     } else {
 7       [].push.apply(a, innerArg)
 8       return _add;
 9     }
10   }
11   return _add
12 }
13 
14 add(1)(2)(3)()    // 6

 

Tooltip:console, alert return 会返回函数和函数执行的结果,劳资两种方法都试了,还尝试了立即执行函数都没有搞好。尼玛,就是少了这个玩意,生气

 

posted @ 2019-07-09 20:07  Bruce_Grace  阅读(5252)  评论(0编辑  收藏  举报