Ways to create a singleton with private variables?

风格不统一 提交于 2019-12-24 08:48:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!