Thursday, February 9, 2012

Javascript OOP - NameSpaces

A fundamental issue with any large code project is maintaining unique identifiers, that is making sure that classes or global functions and variables have unique names. This problem can be mitigated with the use of namespaces. Grouping classes into sets is an explicit feature in many languages that support OOP: Java (packages), Python (modules), and C++(namespaces). JavaScript namespaces are not built in, but are possible with the requisite initiative.

This post demonstrates a simple namespace implementation. Two object prototypes named Person are created in two separate namespaces and thereby avoid convolution.

//if namespace exist use it, otherwise use a new object
var ENG = ENG || {};
//add person to the namespace
ENG.Person = function(){};
ENG.Person.prototype.sayHi = function(){
    console.log("Good Day, My name is John");
}

//if namespace exists use it, otherwise use a new object
var GRM = GRM || {};
//add person to the namespace
GRM.Person = function(){};
GRM.Person.prototype.sayHi = function(){
    console.log("Guten Tag, Ich Heiße Johan");
}

//create two people from two different namespaces.
var englishman = new ENG.Person();
var german = new GRM.Person();

englishman.sayHi(); // Good Day, My name is John
german.sayHi();     // Guten Tag, Ich Heiße Johan

Namespace switching isn't built into JavaScript, so it would be advisable to keep the namespace identifiers short, because they will have to be repeated.

Prominent libraries that encapsulate using namespace like structures:
$ - jQuery, Prototype
THREE - Three.js

For a library that offers a rich set of namespace functionality, investigate Namespace.js.

No comments:

Post a Comment