0

When I do a closure to have private members like in this example by Douglas Crockford

function Container(param) {
  function dec(){
    if (secret > 0) {
      secret -= 1;
      return true;
    } else {
      return false;
    }
  }
  var secret = 3;
  this.service = function(){
    if(dec()){
      return param;
    } else {
      return null;
    }
  };
}

Each instance of Container will have a private secret. What if I wanted all the instances of Container to share access to the same private variable? (there are lots of ways to do this with a public variable of course)

So that a call to any instance of Container would lower secret by 1 and no matter what instance call this.service it could be called only 4 times.

ilyo
  • 35,851
  • 46
  • 106
  • 159

1 Answers1

3

Create the object constructor by using a IIFE and put the secret inside that scope:

var Container = (function(){
  var secret = 3;

  return function(param) {
    function dec(){
      if (secret > 0) {
        secret -= 1;
        return true;
      } else {
        return false;
      }
    }

    this.service = function(){
      if(dec()){
        return param;
      } else {
        return null;
      }
    };
  };
})();
ilyo
  • 35,851
  • 46
  • 106
  • 159
Sirko
  • 72,589
  • 19
  • 149
  • 183
  • So what you basically did is to wrap `Container` in another function so that the returned one will have access to another level of closure? – ilyo Feb 09 '14 at 13:12