Javascript中的静态变量,只设置一次

Jan*_*old 2 javascript oop variables getter setter

我正在撕掉我的头发来完成这个...特别是对于html5检测脚本.我想要一个只设置一次并且不能再次覆盖的变量.就是这个:

var StaticConfiguration = {};
StaticConfiguration.Main = {
    _html5: null
}
StaticConfiguration.getVariable = function(name) {
    return StaticConfiguration.Main["_" + name];
}
StaticConfiguration.setVariable = function(name, value) {
    if(StaticConfiguration.Main["_" + name] == null) {
        StaticConfiguration.Main["_" + name] = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

首先,我定义一个包含所有这些变量的全局对象StaticConfiguration - 在我的例子中,只是"html5".我将它设置为null,因为我想在应用程序中设置它.为此,我打电话

StaticConfiguration.setVariable("html5", "true");
Run Code Online (Sandbox Code Playgroud)

然后就定了.如果我尝试再次设置它,它会失败 - 当然,因为_html5不再是null.所以我几乎使用下划线来"隐藏"静态变量.

这对我很有帮助.我希望这是一个很好的方法 - 请告诉我,如果不是:)

nit*_*k01 5

首先,它true不是"true" 所有字符串(除了空字符串)都评估为true,包括字符串"false".

第二关,你真的需要保护这样的数据吗?无论如何,没有任何方法可以安全地运行用户的Javascript.像这样的保护总是有办法.如果有问题的代码真的得到了关注,那么StaticConfiguration无论如何它都可以取代整个对象.

马修的代码是解决问题的更好方法,但它不遵循单例模式,而是需要实例化的类.如果你想要一个带有"静态"变量的单个对象,我会更喜欢这样做.

StaticConfiguration = new (function()
{
  var data = {}
  this.setVariable = function(key, value)
  {
    if(typeof data[key] == 'undefined')
    {
      data[key] = value;
    }
    else
    {
      // Maybe a little error handling too...
      throw new Error("Can't set static variable that's already defined!");
    }
  };

  this.getVariable = function(key)
  {
    if (typeof data[key] == 'undefined')
    {
      // Maybe a little error handling too...
      throw new Error("Can't get static variable that isn't defined!");
    }
    else
    {
      return data[key];
    }
  };
})();
Run Code Online (Sandbox Code Playgroud)

个人旁注:我讨厌激情格式化"自己的大括号"格式!