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.

Advertisements

One thought on “Namespaces in JavaScript: How To

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s