Is it possible to create a namespace in jQuery?

lpfavreau offers the solution to extend the jQuery object with your own methods (so that their functionality applies on the actual jQuery object context).

If you’re looking to just namespace your code you can use the dollar symbol like this:

$.myNamespace = { .. };

or the “jQuery”:

jQuery.myNamespace = { .. };

Be careful with the namespace you choose as this can overwrite existing jQuery methods (I’d suggest to first search in the jQuery code so that you don’t).

You can follow this link: http://www.zachleat.com/web/2007/08/28/namespacing-outside-of-the-yahoo-namespace/

See how easy it is to create your own function to replicate what YUI does:

// include jQuery first.
jQuery.namespace = function() {
    var a=arguments, o=null, i, j, d;
    for (i=0; i<a.length; i=i+1) {
        d=a[i].split(".");
        o=window;
        for (j=0; j<d.length; j=j+1) {
            o[d[j]]=o[d[j]] || {};
            o=o[d[j]];
        }
    }
    return o;
};

// definition
jQuery.namespace( 'jQuery.debug' );
jQuery.debug.test1 = function()
{
    alert( 'test1 function' );
};
jQuery.debug.test2 = function()
{
    alert( 'test2 function' );
};
// usage
jQuery.debug.test1();
jQuery.debug.test2();

Leave a Comment