JavaScript Namespace Declaration

Usually I'd recommend doing this (assuming Namespace is not defined elsewhere):

var Namespace = {};
Namespace.MyClass = (function () {
  // ...
}());

A more flexible, but more complex, approach:

var Namespace = (function (Namespace) {
   Namespace.MyClass = function() {

       var privateMember = "private";
       function myPrivateMethod(param) {
         alert(param || privateMember);
       };

       MyClass.MyPublicMember = "public";
       MyClass.MyPublicMethod = function (param) {
          myPrivateMethod(param);
       };
   }
   return Namespace
}(Namespace || {}));

This builds Namespace.MyClass as above, but doesn't rely on Namespace already existing. It will declare and create it if it does not already exist. This also lets you load multiple members of Namespace in parallel in different files, loading order will not matter.

For more: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth


YUI has a nice method for declaring namespaces

if (!YAHOO) {
        var YAHOO = {};
}

YAHOO.namespace = function () {
    var a = arguments,
        o = null,
        i, j, d;
    for (i = 0; i < a.length; i = i + 1) {
        d = ("" + a[i]).split(".");
        o = YAHOO;
        for (j = (d[0] == "YAHOO") ? 1 : 0; j < d.length; j = j + 1) {
            o[d[j]] = o[d[j]] || {};
            o = o[d[j]];
        }
    }
    return o;
}

Place it above any function that you want to namespace like this:

YAHOO.namespace("MyNamespace.UI.Controls")

MyNamespace.UI.Controls.MyClass = function(){};
MyNamespace.UI.Controls.MyClass.prototype.someFunction = function(){};

This method is actually stand-alone and can easily be adapted to your application. Just find and replace "YAHOO" with your application's base namespace and you'll have something like MyOrg.namespace. The nice thing with this method is that you can declare namespaces at any depth without having to create object arrays in between, like for "UI" or "Controls"


A succinct way to do what you're asking is create "Namespace" as an object literal like this:

var Namespace = {
    MyClass : (function() {
        ... rest of your module
    })();
};

This could cause conflicts if you wanted to attach other details to Namespace in other files, but you could get around that by always creating Namespace first, then setting members explicitly.