Pacerier
Pacerier

Reputation: 89643

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.__defineGetter__("Asd", function() {
        return asd;
    });
})();

alert(singleton.Asd) // test

However, it seems like alot of ugly code just to achieve a simple thing.

What are some cleaner alternatives to create a singleton with such private variables?

Upvotes: 1

Views: 631

Answers (4)

Alain Duchesneau
Alain Duchesneau

Reputation: 394

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

Upvotes: 2

dheerosaur
dheerosaur

Reputation: 15172

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

console.log(theStaticClass.A);

Upvotes: 3

KooiInc
KooiInc

Reputation: 122916

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):

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

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

Upvotes: 2

ShiningRay
ShiningRay

Reputation: 1008

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.

var TheStaticClass;

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

alert(TheStaticClass.A) // test

Upvotes: 1

Related Questions