Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

oop - Static variable in Javascript that is set only once

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...