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?
com.com.foo. You passcominto the function and the string'com.foo'which adds the nested propertiescomandcom.footo the object you pass in.