[removed]What is meaning of sum(2)(3) //returns 5;

后端 未结 2 1105
感动是毒
感动是毒 2021-01-07 09:58

Here is code blow to return it\'s value.

function sum(a){
  return function(b){
    return a+b;
  }
}
sum(2)(3);

It returns 5 but

2条回答
  •  遥遥无期
    2021-01-07 10:19

    This is called a closure.

    sum(a) returns a function that takes one parameter, b, and adds it to a. Think of it like this:

       sum(2)(3);
    
       // Is equivalent to...
       function add(b){
           return 2+b;
       }
       add(3);
    
       // Which becomes...
       return 2+3; // 5
    

    Your second snippet doesn't work because you're trying to reference b from the outer function, but only the inner function has any notion of what b is. You want to change this:

    function sum(a){
      function add(b){
        return a+b;
      }
      return add(b);
    }
    

    To this:

    function sum(a){
      function add(b){
        return a+b;
      }
      return add; // Return the function itself, not its return value.
    }
    

    Which is, of course, equivalent to the first snippet.

提交回复
热议问题