-1

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.

Tom Tucker
  • 11,676
  • 22
  • 89
  • 130

3 Answers3

4

Not 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.

polarblau
  • 17,649
  • 7
  • 63
  • 84
  • I knew for a fact that JavaScript does not let you define global variables in its own namespace so I figured jQuery might have a solution like always. :D – Tom Tucker Jan 16 '11 at 19:59
  • I might misunderstand you there, but wouldn't the variable `document` in my example now be available globally through the namespace `namespace`? – polarblau Jan 16 '11 at 20:03
  • Yeah it does. I was just answering your question why I wanted to use jQuery at all. – Tom Tucker Jan 16 '11 at 20:06
  • I see. Well, if you still want to use jQuery you could go with boyetboy's approach. But it has a few downsides IMO, you might override something accidentally, e.g.. – polarblau Jan 16 '11 at 20:16
2

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

jmbucknall
  • 2,061
  • 13
  • 14
2

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

Neil
  • 3,229
  • 1
  • 17
  • 15