I use the following code to define a new namespace called com.foo
function extendNamespace(ns, ns_string) {
var parts = ns_string.split('.');
var parent = ns;
for (var i = 0; i < parts.length; i++) {
//create a property if it doesnt exist
if (typeof parent[parts[i]] == 'undefined') {
parent[parts[i]] = {};
}
parent = parent[parts[i]];
}
return ns;
}
var com = {};
extendNamespace(com, "com.foo");
console.log(com); // OK (even has an object called "foo"!!)
console.log(com.foo); // Undefined ???
The first call of console.log(com) clearly shows me in console that a new object “com” has been created which has an object called “foo”.
So far, so good.
The second call console.log(com.foo); though returns me “undefined”.
What gives?
No. It has a property called
com, the value of which is an object with a property calledfoo.You are extending
comwithcom.foowhen you only want to extend it withfoo.