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.
[...] Namespaces in JavaScript: How To [...]