How can I make var a = add(2)(3); //5 work?

后端 未结 28 2337
长发绾君心
长发绾君心 2020-11-27 14:11

I want to make this syntax possible:

var a = add(2)(3); //5

based on what I read at http://dmitry.baranovskiy.com/post/31797647

I\

相关标签:
28条回答
  • 2020-11-27 14:51

    Concept of CLOSURES can be used in this case.
    The function "add" returns another function. The function being returned can access the variable in the parent scope (in this case variable a).

    function add(a){
    
        return function(b){
            console.log(a + b);
        }
    
    }
    
    
    add(2)(3);
    

    Here is a link to understand closures http://www.w3schools.com/js/js_function_closures.asp

    0 讨论(0)
  • 2020-11-27 14:52
    function A(a){
      return function B(b){
          return a+b;
      }
    }
    

    I found a nice explanation for this type of method. It is known as Syntax of Closures

    please refer this link Syntax of Closures

    0 讨论(0)
  • 2020-11-27 14:52

    function add () {
        var args = Array.prototype.slice.call(arguments);
     
        var fn = function () {
            var arg_fn = Array.prototype.slice.call(arguments);
            return add.apply(null, args.concat(arg_fn));
        }
     
        fn.valueOf = function () {
            return args.reduce(function(a, b) {
                return a + b;
            })
        }
     
        return fn;
    }
    
    console.log(add(1));
    console.log(add(1)(2));
    console.log(add(1)(2)(5));

    from http://www.cnblogs.com/coco1s/p/6509141.html

    0 讨论(0)
  • 2020-11-27 14:55

    try this will help you in two ways add(2)(3) and add(2,3)

    1.)

     function add(a){ return function (b){return a+b;} }
    
        add(2)(3) // 5
    

    2.)

    function add(a,b){
            var ffffd = function (b){return a+b;};
            if(typeof b =='undefined'){
                return ffffd;
            }else{
                return ffffd(b);
            }
        }
    
    add(2)(3) // 5
    add(2,3) // 5
    
    0 讨论(0)
  • 2020-11-27 14:55

    let multi = (a)=>{
    	return (b)=>{
    		return (c)=>{
    			return a*b*c
    		}
    	}
    }
    multi (2)(3)(4) //24

    let multi = (a)=> (b)=> (c)=> a*b*c;
    multi (2)(3)(4) //24

    0 讨论(0)
  • 2020-11-27 14:56

    It's about JS curring and a little strict with valueOf:

    function add(n){
      var addNext = function(x) {
        return add(n + x);
      };
    
      addNext.valueOf = function() {
        return n;
      };
    
      return addNext;
    }
    
    console.log(add(1)(2)(3)==6);//true
    console.log(add(1)(2)(3)(4)==10);//true
    

    It works like a charm with an unlimited adding chain!!

    0 讨论(0)
提交回复
热议问题