How do I create a globally accessible variable?

前端 未结 3 498
你的背包
你的背包 2021-01-25 03:28

I\'m trying to make a variable thats can work anywhere, and just not in one function.

How do i do this? I\'ve searched for like 1 hour now and i can\'t find it :(

<
相关标签:
3条回答
  • 2021-01-25 03:39

    you can create a public function that has access to the private variables like this

    function Person() {
        var secret = "Secret Message";
    
        this.revealSecret = function() {
            return secret;
        }
    }
    var me = new Person();
    me.revealSecret(); //returns "Secret Message"
    
    0 讨论(0)
  • 2021-01-25 03:40

    you can always use the window object to attach your "global" variable, but not a very good idea, could cause collisions with other usages

    window.noneTxt = document.innerHTML="Nothing is playing!";
    
    0 讨论(0)
  • 2021-01-25 03:57

    If you can manage multiple JS files, create a new javascript file called something like "globals.js" and put all your global variables there:

    var g1 = "this is a global var";
    var g2 = "another global var";
    

    Then use these vars in other files freely, as long you remember to include this file in each page you load.

    The 'globals.js' file can also include convenience functions like 'getVar(varname)'.

    Another step up would be to have a single variable which is a collection, and a function that gets a key and returns the corresponding variable from the collection. The function may also check if a variable exists, and return a default value if not:

    var globals = {
      g1: "this is a global var",
      g2: "another global var"
    };
    
    function getGlobalVar(varname) {
      if (typeof(globals[varname]) === 'undefined') {
        return "some default";
      } else {
        return globals[varname];
      }
    }
    

    -DBG

    0 讨论(0)
提交回复
热议问题