问题
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?
回答1:
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
回答2:
var theStaticClass = (function () {
var a = 7;
return { get A() { return a; } };
})();
console.log(theStaticClass.A);
回答3:
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
回答4:
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
来源:https://stackoverflow.com/questions/5731039/ways-to-create-a-singleton-with-private-variables