title: How can I make privileged JS methods?
body: <p>I want to be able to call sub-functions that work with private data. Currently I have this:</p>
  
  <pre><code>var myFunction4 = function() {
    this.secret1 = 0;
    this.secret2 = 0;
    var that = this;
  
    this.iterate1 = function(){
      return that.secret1++;
    }
  
    this.iterate2 = function(){
      return that.secret2++;
    }
  
    this.addSecrets = function(){
      return that.secret1 + that.secret2;
    }
  
    return {
        iterate1: this.iterate1,
        iterate2: this.iterate2,
        addSecrets: this.addSecrets,
    }
  };
  </code></pre>
  
  <p>The bad thing about this is that to call one of the methods, I have to do:</p>
  
  <pre><code>myFunction4().iterate1();
  </code></pre>
  
  <p>Which executes <code>myFunction4()</code>  every single time I want to access a method. Not only is this inefficient, but it resets <code>secret1</code> each time so I can't iterate it. I've tried using the <code>new</code> operator, but that exposes <code>secret1</code> and <code>secret2</code>, and it messes up the ability to nest functions deeply. </p>
  
  <pre><code>var myFunction3 = function() {
    this.secret1 = 0;
    this.secret2 = 0;
  
    this.iterate1 = function(){
      return this.secret1++;
    }
  
    this.iterate2 = function(){
      return this.secret2++;
    }
  
    this.addSecrets = function(){
      return this.secret1 + this.secret2;
    }
  };
  var f3 = new myFunction3();
  f3.secret1; // exposes the secret!
  </code></pre>
  
  <p>See the <a href="https://jsfiddle.net/75gb1zkd/" rel="nofollow">console logs at the bottom of this JSFiddle</a> for more examples. </p>
  
  <p>How can I have a function with both private and public vars/methods which retain their values and don't need to be called multiple times?</p>