Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I was tearing my hair out to get this done...particularly for an html5 detection script. I wanted a variable that is set only once and that can't be overwritten again. This is it:

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;
    }
}

First, I define a global object StaticConfiguration containing all of these variables - in my case, just "html5". I set it to null, since I want to set it inside the application. To do so, I call

StaticConfiguration.setVariable("html5", "true");

It's set then. If I try to set it again, it fails - of course, since _html5 is not null anymore. So I practically use the underscore to "hide" the static variable.

This is helping me a lot. I hope it's a good approach - please tell me if not :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

First off, it's true, not "true" all strings (apart from the empty string) evaluate to true, including the string "false".

Second off, do you really need to protect data like this? There's not really any way to safely run a user's Javascript i your context anyway. There's always a way around protection like this. If offending code really cared, it could just replace the whole StaticConfiguration object anyway.

Matthew's code is a better approach to the problem, but it doesn't follow a singleton pattern, but is a class that needs to be instanciated. I'd do it more like this, if you wanted a single object with "static" variables.

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];
    }
  };
})();

Personal sidenote: I hate the "curly brackets on their own lines" formatting with a passion!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...