« 5 Free Grunge Webdesign Textures | Main | Flex/AIR: DynamicEvent »
Monday
Jul052010

Namespaces in JavaScript: How To

Writing JavaScript code can rapidly become messy because of its procedural nature (Object-based as opposed to Object-Oriented). Generally you create variables at the top of your .js-file, followed by functions below. Besides general ugliness, you must remember that such variables are globally accessible from other scripts. This practice implies serious security and privacy issues. To amend this, you can turn to namespaces in JavaScript, and here's how it works.

Conceptually, namespaces in JavaScript involve creating a stored function. This function subsequently contains private variables, private functions and public functions by means of the return construct:

var SomeNamespacedObject = function() {
// private vars
///////////////
var somePrivateVar;
var anotherPrivateVar;

// private functions
////////////////////
function doSomethingPrivate() {
// private business goes here
}

// public functions
///////////////////
return {
doPublicStuff : function() {
// public business goes here
},
doMorePublicStuff : function() {
// more public business
}
}
}();

You can now reference your namespaced object like so:

SomeNamespacedObject.doPublicStuff();

Namespacing introduces some pros and cons, but I generally namespace my JS code, sometimes only for the sake of making it look more object oriented. Also, it makes me sleep better at night knowing not all of my variables are being broadcast publicly and I'm not polluting the global variable space.

Pros:

  • Cleaner
  • Encourages code reuse
  • Encourages encapsulation (private vs. public)
  • Prevents overwriting of existing functions

Cons:

  • Verbose
  • Perhaps a bit confusing to JS newbies

My advice? Namespace that JavaScript, my friend.

Reader Comments (1)

[...] Namespaces in JavaScript: How To [...]

July 4, 2010 | Unregistered CommenterGadget Newz

PostPost a New Comment

Enter your information below to add a new comment.

My response is on my own website »
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>