1

Am I doing something wrong or is this just not possible:

(function(namespace,undefined)
{
    //Private properties and methods
    var foo="bar";
    function test(){return foo;}

    //Public properties and methods
    namespace.foobar=foo+"123";
    namespace.showFoo=function(){return test();};
})(window.namespace=window.namespace || {});

Then I try to "extend" the above namespace and add a new method:

(function(namespace,undefined)
{
    //Public method
    namespace.sayGoodbye=function()
    {
        alert(namespace.foo);
        alert(namespace.bar);
        alert(test());
    }
})(window.namespace=window.namespace || {});

The alert shows undefined for the properties and throws an error for the test() method.

Thanks.

3 Answers 3

3

Why would you expect to have foo and bar available ? Those identifiers are never assigned to your namespace object anywhere.

Any variable that is declared with var is only available in the Function(-Context) of the current Activation/Variable Object. Same goes for function declarations, in your case, test(). Both these are only stored within the AO from the first anonymous function and are not stored within your namespace object. You would have to explicitly assign the values

namespace.foo = foo;
namespace.bar = "hello I am bar";
Sign up to request clarification or add additional context in comments.

1 Comment

OK, was thinking too OOP. Thanks.
1

You have several bugs in your code. That code is working. Example.

(function(namespace)
{
    if(namespace === undefined) {
        window.namespace = namespace = {};
    }

    //Private properties and methods
    var foo="bar";
    function test(){return foo;}

    //Public properties and methods
    namespace.foobar=foo+"123";
    namespace.showFoo=function(){return test();};
})(window.namespace);

(function(namespace)
{
    if(namespace === undefined) {
        window.namespace = namespace = {};
    }

    //Public method
    namespace.sayGoodbye=function()
    {
        alert(namespace.foobar);
        alert(namespace.showFoo());
    }
})(window.namespace);

window.namespace.sayGoodbye();

Bugs: 1. You never set the variable window.namespace. 2. If you declare variables/functions in a private way in a function then only this specific function can access these variables/functions. If you want to use a namespace you can do it like this:

var namespace = (function(){
        var private = "private";
        function privateFunc() {
                return private;
        }
        return {
            "publicFunc": function(){return privateFunc()}
        }
    })();
namespace.publicFunc() === "private";
//alert(namespace.publicFunc());


// extend namespace
(function(namespace){
    var private = "other private";
    namespace.newFunc = function(){return private};
})(namespace);
namespace.newFunc() === "other private";
//alert(namespace.newFunc());

1 Comment

Regarding what you've identified as "bug 1", the code in the question does set window.namespace, in the parameter passed to each anonymous fiction it assigns it to itself if it already exists or to an empty object otherwise. I.e., it extends or creates as needed.
1

Namespaces declaration and extending of namespaces:

var namespace = function(str, root) {
    var chunks = str.split('.');
    if(!root)
        root = window;
    var current = root;
    for(var i = 0; i < chunks.length; i++) {
        if (!current.hasOwnProperty(chunks[i]))
            current[chunks[i]] = {};
        current = current[chunks[i]];
    }
    return current;
};

// ----- USAGE ------

namespace('ivar.util.array');

ivar.util.array.foo = 'bar';
alert(ivar.util.array.foo);

namespace('string', ivar.util); //or namespace('ivar.util.string');

ivar.util.string.foo = 'baz';
alert(ivar.util.string.foo); 

Try it out: http://jsfiddle.net/stamat/Kb5xY/

Blog post: http://stamat.wordpress.com/2013/04/12/javascript-elegant-namespace-declaration/

Comments

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.