JavaScript namespace
I would like to introduce you to an approach of defining namespace in JavaScript.
JavaScript itself does not have capability of namespacing, but we can use its basic
concepts to create namespace. The idea is to create multiple object that will mimic
namespace, for example:
com.javascript.namespace
Here we have the object com which hold the object javascript and in it the object namespace
in which we can define the objects in the “com.javascript.namespace” namespace.
Fist approach is to create these objects by ourselves like so (JSON):
var com = { javascript: { namespace: {} } }; // our object here com.javascript.namespace.myObject = {};
We can do this automaticly:
NAMESPACE_CREATOR = { createNamespace: function(namespace){ var o = null; if(typeof namespace == 'undefined'){ // nothing to create return; } var tts = namespace.split('.'); eval('if(typeof' + tts[0] + '== "undefined"){' + tts[0] + '= {}; } o = tts[0];'); for(var i = 1; i < tts.length; i++){ o[tts[i]] = o[tts[i]] || {}; o = o[tts[i]]; } } };
Decopmosed:
var o = null;
“o” will serv as refernce to the current object in the namespace hierarchy.
var tts = namespace.split('.');
We need to know all object that we will need to create. But we must create the top-hierarchy object first so:
eval('if(typeof' + tts[0] + '== "undefined"){' + tts[0] + '= {}; } o = tts[0];');
Kinda confusing?
Well this is what it will evaluates to:
Let suppose we have this call:
NAMESPACE_CREATOR.createNamespace("com.js.namespace");
it evaulates to:
if(typeof com == "undefined"){ com = {}; } o = com;
So the we have reference to “com” in “o”, and “com” is empty object (if not already defined).
Since we have the top-hierarchy object we can do the following:
for(var i = 1; i < tts.length; i++){ // o[tts[i]] is same as o.something // lets say tts[i] = "js" // o[tts[i]] = o.js // so, if it is not defined already, we'll define it to an empty object o[tts[i]] = o[tts[i]] || {}; // switch from o to o[tts[i]] // eg. if o=com and tts[i] = "js" // o[tts[i]] = com.js // so o = com.js o = o[tts[i]]; }
Usage example:
NAMESPACE_CREATOR.createNamespace("com.js.namespace.myNamespace"); com.js.namespace.myNamespace.myProperty = {msg:"so not cool"}; com.js.namespace.myNamespace.numberProperty = 1000;
funstufz