What's the recommended approach for namespace handling in javascript?

Hey,

We have a set of javascript "modules" organized in "namespaces" - object hierarchy rooted in the global object (window).

In some cases we use an utility createNs("namespace.name")(it works exactly like YUI

YAHOO.namespace()
), however we have no intellisense with it.

For now, the only way to make IntelliSense work is writing extremely bothering stuff like the following:

(function (window) {
    // no dependencies
    var ourCompany = window.ourCompany || (window.ourCompany = {});
    var components = ourCompany.components || (ourCompany.components = {});
    var emails = components.emails || (components.emails = {});
    emails.inbox = {
        checkNew: function() {
        }
    };
})(window);

(function (window) {
    // consumer
    window.ourCompany.components.emails.inbox.checkNew();
})(window);



Another option is using jQuery.extend method which is not always available:

(function (window, $) {
    // depends on jquery
    $.extend(true, window, {
        ourCompany: {
            components: {
                emails: {
                    inbox: {
                        checkNew: checkNew
                    }
                }
            }
        }
    });
    function checkNew() {
    }
})(window, jQuery);



What's the common denominator solution?

  • Write less,
  • Have intellisense,
  • Have ReSharper's refactorings,
  • No 3rd party dependencies

Is it possible?

Thanks!

Please sign in to leave a comment.