Reputation: 89643
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
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
Reputation: 15172
var theStaticClass = (function () {
var a = 7;
return { get A() { return a; } };
})();
console.log(theStaticClass.A);
Upvotes: 3
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
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