Skip to content Skip to sidebar Skip to footer

Ways To Create A Singleton With Private Variables?

I'm trying to create a singleton that has variables not directly mutable from the outside. This is my current code: var singleton = new (function () { var asd = 1; this.__d

Solution 1:

var theStaticClass = (function () {
    var a = 7;
    return { getA() { return a; } };
})();

console.log(theStaticClass.A);

Solution 2:

This is another (I wouldn't say less ugly) way, but now TheStaticClass.A is more like a getter method (the advantage being that it also works in IE):

varTheStaticClass = new (function() {
  var a=1;
  arguments.callee.prototype.A = function() {
    return a;
  };
})();

alert(TheStaticClass.A()) //=> 1

Solution 3:

Suppose you need to do some modifications to the variable before returning:

var theStaticClass = (function () {
    var a = 7;
    return {A: (function(b){
        return b * b;
    })(a)};
})();
console.log(theStaticClass.A); // => 49

Solution 4:

I think only closure can bring real private variable in JavaScript. Usually we use some kind of naming convention to tell if the variable is private.

varTheStaticClass;

(function () {
  var a=1;
  TheStaticClass.__defineGetter__("A", function() {
    return a;
  });
})();

alert(TheStaticClass.A) // test

Post a Comment for "Ways To Create A Singleton With Private Variables?"