Domanda

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.

È stato utile?

Soluzione

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;
      }
    };
  };
})();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top