Namespace

Organizes the code to avoid name collisions.

jQuery makes use of the Namespace pattern in its code base.



Overview


jQuery makes use of namespaces. A goal of the Namespace pattern is to limit the number of variables introduced to the global namespace to just a single name. This single global item (object) then contains the entire code base for the application or library.

This is exactly how jQuery is organized: a single object, named jQuery, holds the entire body of code, including variables, properties, methods, and other (nested) namespaces. Example nested namespaces include event, and support which are referenced as jQuery.event and jQuery.support respectively.

Actually, jQuery cheats a bit on the namespace pattern as it adds not one but two names to the global namespace, the second one being $ which is just shorthand for jQuery. The $ is referred to as an alias of jQuery. In your code you can replace any $ occurrence with jQuery and vice versa; they are the same and this will not change your code.

The statement below is from jQuery. It shows how the global names are exported.

// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;

You find this line at the bottom of the jQuery source file.


Another area where jQuery uses namespacing is with events. When attaching an event you can quality your event name with a namespace, something like this: click.Framework.User:

$("#name").on("click.Framework.User ", function() { alert("clonk"); };

This will add click to the Framework and User namespace. Namespaces with events are not hierarchical; instead, each name is just a separate namespace. Our event is part of both the Framework namespace and the User namespace (and not the Framework.User namespace).

This mechanism allows you to selectively detach event handlers without affecting any other click handler:

$("#name").off("click.Framework"};
$("#name").off("click.User"};

The two lines above have the same effect, as our click event is part of both namespaces.



  Chaining
Lazy Load