title: Puzzle: JS Function that returns itself until there are no arguments
body: <p>I'm trying to solve a puzzle, and am at my wit's end trying to figure it out.</p>
  
  <p>I'm supposed to make a function that works like this:</p>
  
  <pre><code>add(1);       //returns 1
  add(1)(1);    //returns 2
  add(1)(1)(1); //returns 3
  </code></pre>
  
  <p>I know it can be done because other people have successfully completed the puzzle.  I have tried several different ways to do it.  This is my most recent attempt:</p>
  
  <pre><code>function add(n) {
      //Return new add(n) on first call
      if (!(this instanceof add)) {
          return new add(n);   
      }
  
      //Define calc function
      var obj = this;
      obj.calc = function(n) {
          if (typeof n != "undefined") {
              obj.sum += n;
              return obj.calc;            
          }
  
          return obj.sum;
      }
  
      //Constructor initializes sum and returns calc(n)
      obj.sum = 0;
      return obj.calc(n);
  }
  </code></pre>
  
  <p>The idea is that on the first call, a new <code>add(n)</code> is initialized and <code>calc(n)</code> is run.  If <code>calc</code> receives a parameter, it adds <code>n</code> to <code>sum</code> and returns itself.  When it eventually doesn't receive a parameter, it returns the value of <code>sum</code>.</p>
  
  <p>It makes sense in theory, but I can't get it to work.  Any ideas?</p>
  
  <p>--edit--</p>
  
  <p>My code is just the route I chose to go.  I'm not opposed to a different approach if anyone can think of one.</p>