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

Leave a Comment