How do I create a globally accessible variable?

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 :(

I tried this

noneTxt = document.innerHTML="Nothing is playing!";

function plinf() {
    if (myAudio.paused) {
        myAudio.play();
    }
    else {
    myAudio.pause();
    document.getElementById('message').innerHTML=noneTxt;
    }
}

But it only works if I put the variable inside the function with var prefix... So how can i make it kinda global? :/

Answers:

Answer

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!";
Answer

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"
Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.