JavaScript Namespace Declaration

I created a javascript class as follow:

var MyClass = (function() {
   function myprivate(param) {
      console.log(param);
   }

   return {
      MyPublic : function(param) {
         myprivate(param);
      }
   };
})();

MyClass.MyPublic("hello");

The code above is working, but my question is, how if I want to introduce namespace to that class.

Basically I want to be able to call the class like this:

Namespace.MyClass.MyPublic("Hello World");

If I added Namespace.MyClass, it'll throw error "Syntax Error". I did try to add "window.Namespace = {}" and it doesn't work either.

Thanks.. :)


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.

链接地址: http://www.djcxy.com/p/17064.html

上一篇: 为什么我在jQuery中封装jQuery函数(function($){});

下一篇: JavaScript命名空间声明