How to store a global value (not necessarily a global variable) in jQuery?

You can create a hash in the global scope and use it as a namespace:

MyNamepace={}
MyNamespace.newvar = 'value'
// MyNamespace.newvar => 'value'

For me the best way to handle this situation is to define an object in the window object:

window.my_config =
{
    my_var1 : 1,
    my_var1 : 2,
    my_var1 : 3
};

This would keep your scope neat and clean. And whenever you would access the global using window.my_config anyone looking at the code would know that a global is being accessed.


You can create a namespace inside the jQuery object, like so:

$.mynamespace = { 
    myVar : "something", 
    myVar2 : "somethingElse" 
}; 

or:

$.mynamespace = {};
$.mynamespace.myVar = "something";
$.mynamespace.myVar2 = "somethingElse";

Bear in mind, any plugin method named 'mynamespace' will be overwritten so be sure to use a sensible name.


Just sharing my practice with you, I would make a global object/var in the required JavaScript file with a sensible prefix, as in if I am working on a page where this object will be a text box then I would name it:

g_TxtMyValue = 'value';    // g_ specifies it to be a global variable, it is one
                           // of the many conventions used

If you have more than one global variable, you can also have a namespace such as:

my_txt = {};  // For a real site I would use a prefix relative to the project
              // name instead of "my".

my_txt.testValueOne = 'Value one';
my_txt.testValueOne = 'Value two';

These variables will be available to you throughout the website, after they have been initialized.

I hope this helps.