Last Updated: 25 Jul 2023

   |   

Author: dordal

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
front-end-tech:javascript:namespacing-and-aliasing-namespaces-in-javascript [May 12, 2008 08:47 AM]
dordal
front-end-tech:javascript:namespacing-and-aliasing-namespaces-in-javascript [Jul 25, 2023 05:28 AM]
dordal old revision restored (Nov 21, 2020 10:39 PM)
Line 1: Line 1:
 += 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 [[http://developer.yahoo.com/yui/|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.
 +
 +<code javascript>
 +// 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];
 +}
 +</code>
 +
 +**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:
 +<code javascript>
 +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');
 +</code>