Nicer way of checking JavaScript namespace
I'd try something like this although it is prone to error if it receives some funky input:
if(check("TOP.middle.realModuleName")) {
//exists
}
//namespace checking function
function check(ns) {
var pieces = ns.split('.'),
current = window;
for(i in pieces) {
if(!(current = current[pieces[i]])) {
return false;
}
}
return true;
}
You can use a try/catch and look for 'not_defined
':
try {
TOP.middle.realModuleName = function () { /*...*/ };
} catch(e) {
if ( e.type == 'not_defined' ) {
// exception
}
else {
// throw other errors
throw e;
}
}
just encapsulate it in a TRY/CATCH?
try {
return new TOP.middle.blablabla();
}
catch(err) {
// oh no!
}
return null;
Try this simple helper function:
function exists(namespace) {
var tokens = namespace.split('.');
return tokens.reduce(function(prev, curr) {
return (typeof prev == "undefined") ? prev : prev[curr];
}, window);
}
It takes a String
as input and will return the object if it exists. You can use it like this:
var module = exists("TOP.middle.realModuleName");
For example:
exists("noexist"); // returns undefined
exists("window"); // returns DOMWindow
exists("window.innerHeight"); // returns Number
exists("window.innerHeight.toString"); // returns Function
exists("window.innerHeight.noexist"); // returns undefined
It also works properly for expressions that evaluate to false:
testNum = 0;
testBool = false;
testNull = null;
exists("testNum"); // returns 0
exists("testBool"); // returns false
exists("testNull"); // returns null