JavaScript Namespacing Fun

Tags

, ,

In an attempt to ensure you avoid collisions you really should be using namespacing in Javascript. Here is something with some examples to get you started.

window.namespace = (function () {

    function wrap(namespace){
        return {
            namespace : namespace,
            extendWith : function(subnamespace,literal){
                if (!(this.namespace.hasOwnProperty(subnamespace))) {
                    this.namespace[subnamespace] = literal;
                    return wrap(this.namespace[subnamespace]);
                }
                return this;
            },
            extend : function(subnamespace){
                if (!(this.namespace.hasOwnProperty(subnamespace))) {
                    this.namespace[subnamespace] = {};
                    return wrap(this.namespace[subnamespace]);
                }
                return this;
            },
            append : function(functionname, f){
                if (!(this.namespace.hasOwnProperty(functionname))) {
                    this.namespace[functionname] = f;
                }
                return this;
            }
        };
    }
    
    function head(array) {
        return array[0];
    }

    function tail(array) {
        return array.slice(1);
    }

    function build(prefix, namespaceParts) {
        if (namespaceParts.length == 0) {
            return prefix;
        }

        var headElement = head(namespaceParts);

        if (!(prefix.hasOwnProperty(headElement))) {
            prefix[headElement] = {};
        }

        return build(prefix[headElement], tail(namespaceParts))
    }

    return {
        apply: function (namespace) {
            if (!(namespace && namespace.length > 0)) {
                return wrap(window);
            }

            var namespaceComponents = namespace.split('.');
            return wrap(build(window, namespaceComponents));
        }
    };
}());


var result = namespace.apply("kiandra.local")
         //.extend("messages",{show : function() { alert("Hi");}})
         .extend("messages")
         .extendWith("next", {showNext : function() { alert("Hi Again");}})
         .append("detailed",function(){ alert("detailed"); })
         .append("console",function(){ alert("console"); });

console.log(result);

//kiandra.local.messages.show();
kiandra.local.messages.next.console();
kiandra.local.messages.next.showNext();

Blair

Follow

Get every new post delivered to your Inbox.

Join 211 other followers