1

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?

2
  • 5
    If you have a closer look, you'll that the structure is com.com.foo. You pass com into the function and the string 'com.foo' which adds the nested properties com and com.foo to the object you pass in. Commented Aug 17, 2012 at 21:35
  • @Felix If you had just posted this as the answer you'd have 40 points already. The 3 comment votes + my vote. Commented Aug 17, 2012 at 21:38

1 Answer 1

4

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".

No. It has a property called com, the value of which is an object with a property called foo.

You are extending com with com.foo when you only want to extend it with foo.

Sign up to request clarification or add additional context in comments.

1 Comment

You're right! So the correct call would be extendNamespace(com, "foo");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.