Closure in Javascript with multiple brackets

前端 未结 5 600
梦谈多话
梦谈多话 2021-02-01 21:00

Could any one explain how this function alert, when more no of brackets of parameters are passed. I could not able to understand it clearly.

function sum(a) {

          


        
5条回答
  •  花落未央
    2021-02-01 21:55

    The first time your function is called, the first value is stored in sum. After that function f(b) will be returned, maintaining the provisional result in sum. With each consecutive call you execute function f - you perform sum += b and return f again. If a string context is required (such as in the alert, or a console.log) f.toString is called instead, returning the result (sum).

    function sum(a) {
    
      var sum = a
    
      function f(b) {
        sum += b
        return f  //<- from second call, f is returned each time
                  //   so you can chain those calls indefinitely
                  //   function sum basically got "overridden" by f
      }
    
      f.toString = function() { return sum }
    
      return f //<- after first call, f is returned
    }
    

    Explanation:

    alert( sum(6)(-1)(-2)(-3) )  // 0
               /\ function sum called, f returned
                  /\ the returned function f is called, f returns itself
                      /\ again
                         /\ and again
                             /\ at last, alert() requires string context,
                                so f.toString is getting invoked now instead of f
    

提交回复
热议问题