简体   繁体   中英

how to get the same result by using function and closure together in javascript

I need to make the following(below) function call to give the same result in both situations:

sum(5,4);   // 9
sum(5)(4);   // this should also print 9

I tried the following but it's not working:

function sum(x,y){

   var a = x;
   var b = y;

   if (y == undefined && y == ''){
   return function (a,b){
      return a +b;
      }
   }
   else {
     return a +b;
   }

 }

Any suggestions?

Try to curry your function for your requirement,

function sum(x,y){
  if(y === undefined){
    return function(y){ return x+y; }
  } else { 
      return x + y; 
  }
}

sum(5,4);   // 9
sum(5)(4);  // 9

You should use logical OR (||), not AND (&&)

function sum(x,y){
   if (y == undefined || y == ''){
      return function (y){
        return x + y;
      }
   }
   else {
     return x + y;
   }
}

The "cool" one line answer:

function sum(x, y){ 
   return y != undefined? x+y : function(a){return x + a}; 
}

Careful: You probably won't need that functionality, it's simply redundant.

You can use conditioning like that:

function sum( x , y ){
  if(y == undefined){
    return function( y ){
      return x + y;
    };
  }
  else{
    return x + y;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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