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

Solution 1:

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.

Solution 2:

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.

Solution 3:

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

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