Is there a way to declare a global variable in jQuery in its own namespace?
Sure, I can declare global variables with plain old JavaScript, but they will fall in the window
's namespace. For example, if I had a variable named document
, it would surely overwrite the document
object of the window
.
Does jQuery have a hash table that lets you store any object by their name?
Thanks.
Is there a way to declare a global variable in jQuery in its own namespace?
Sure, I can declare global variables with plain old JavaScript, but they will fall in the window
's namespace. For example, if I had a variable named document
, it would surely overwrite the document
object of the window
.
Does jQuery have a hash table that lets you store any object by their name?
Thanks.
Share Improve this question asked Jan 16, 2011 at 19:53 Tom TuckerTom Tucker 11.9k23 gold badges95 silver badges131 bronze badges3 Answers
Reset to default 4Not sure why you want to use jQuery for that? You could just create your own namespace:
var namespace = {
document : "Foo"
};
Please elaborate, if there's some need to use jQuery somehow.
Of course you can. Create a namespace as an object and then attach it to the jQuery function.
(function ($) {
$.myNamespace = {};
})(jQuery);
Here I've created an auto-executing anonymous function to do the work. I can then add other propertes and functions to the namespace inside this function. Also this avoids the problem of someone else renaming $
to something else.
After this is done you can refer to your namespace as jQuery.myNamespace
If the variable is something that want to associate with an element to be used later, maybe in a different routine, you could use jQuery's "data" method to store it.
e.g.
:
:
// Save original HTML content.
var old_html = $('#box').html();
$('#box').data({originalContent: old_html});
// Replace with new content.
$('#box').empty().html(new_html);
:
// Restore original content (maybe in a different function).
var orig_html = $('#box').data('originalContent');
$('#box').empty().html(orig_html);
:
I hope this is useful to you.
Regards Neil