Last Updated: 25 Jul 2023

   |   

Author: dordal

Namespacing & Aliasing Namespaces in JavaScript

Javascript has an implied global namespace. This means any functions, variables, etc. that you create are put into the global namespace by default. If you're writing a lot of JavaScript code, it can be a good idea to put your own code into your own namespace. It's doubly important if you are going to share that code with the world. The Yahoo YUI people do this, for example.

To do this, create an object. As a convention, I like to start the name of the object with a $ to indicate it is a namespace. Then declare your functions inside your new namespace. You may even want to declare sub-namespaces to group functions.

// Make sure the $O namespace exists ($O is a random name; it can be anything)
var $O = window.$O || {};     
 
// Create a sub-namespace for admin functions
$O.admin = {};               
 
// create an array in the main $O namespace
$O.usernames = ['dordal','kate','jane'];  
 
// create a function in the admin sub-namespace, that uses a variable from the main namespace.
$O.admin.getUsername = function(arrayIndex) {     
 return $O.usernames[arrayIndex];
}

IMPORTANT: You'll generally want to access any functions with their fully qualified name, e.g. $O.admin.getUsername, not just getUsername()

Aliasing Namespaces

You can alias other people's namespaces (and even functions) to make them easier to remember. I like to do this with the YUI stuff:

var $D = YAHOO.util.Dom;
var $E = YAHOO.util.Event;
var $El = YAHOO.util.Element;
var $ = $D.get;
 
// Now, I can access functions more simply:
$D.getElementsByClassName('someElementId');     // instead of YAHOO.util.Dom.getElementsByClassName()
 
// Above, I've even aliased YUI's 'get' function, which means I can get any element simply by saying:
var myElementVar = $('someElementId');

Discussion

89.146.76.200, Jan 29, 2009 05:41 PM

Great article. Here is an article on how to use it with the jQuery object. In other words namespasing with the jQuery http://jquery-howto.blogspot.com/2009/01/namespace-your-javascript-function-and.html

Enter your comment. Wiki syntax is allowed: