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()
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');