JavaScript命名空间声明 [英] JavaScript Namespace Declaration

查看:107
本文介绍了JavaScript命名空间声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个javascript类如下:

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");

如果我添加了Namespace.MyClass,它将抛出错误语法错误。
我确实尝试添加window.Namespace = {}并且它也不起作用。

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

谢谢.. :))

推荐答案

通常我建议这样做(假设命名空间未在其他地方定义):

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 || {}));

如上所述构建 Namespace.MyClass ,但不依赖 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更多: http://www.adequatelygood.com/2010/3 / JavaScript-Module-Pattern-In-Depth

这篇关于JavaScript命名空间声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆