【问题标题】:Javascript Namespace - Multiple LevelsJavascript 命名空间 - 多层次
【发布时间】:2011-12-11 02:41:15
【问题描述】:

我目前正在执行以下操作来为我的 javascript 代码提供命名空间:

(function(foo, $, undefined) {
    // function: showNoteDialog
    foo.showNoteDialog = function() {
       // ...
    }
}(window.foo = window.foo || {}, jQuery));

我更喜欢的是:

foo.showNoteDialog()

是要有一个多级命名空间:

foo.notes.showDialog()
foo.other.showDialog()

这可能吗?我该怎么做?

【问题讨论】:

    标签: javascript javascript-namespaces


    【解决方案1】:

    这是我通常的做法:

    var TopLevel = TopLevel || {}; //Exentd or Create top level namespace
    TopLevel.FirstChild = TopLevel.FirstChild || {}; //Extend or Create a nested name inside TopLevel
    

    使用这种方法可以保证文件之间的安全。如果 TopLevel 已经存在,您将其分配给 TopLevel 变量,如果不存在,您将创建一个可以扩展的空对象。

    因此,假设您要创建一个存在于 Application 命名空间中并在多个文件中扩展的应用程序,您可能希望文件看起来像这样:

    文件 1(库):

    var Application = Application || {};
    
    Application.CoreFunctionality = Application.CoreFunctionality || {};
    Application.CoreFunctionality.Function1 = function(){
      //this is a function
    }//Function1
    

    文件 2(库):

    var Application = Application || {};
    
    Application.OtherFunctionality = Application.OtherFunctionality || {};
    Application.OtherFunctionality.Function1 = function(){
      //this is a function that will not conflict with the first
    }
    

    文件 3(工作人员):

    //call the functions (note you could also check for their existence first here)
    Application.CoreFunctionality.Function1();
    Application.OtherFunctionality.Function1();
    

    【讨论】:

      【解决方案2】:

      看看namespace.js。它允许您使用公共和私有方法声明嵌套命名空间。这很好,因为它允许您在没有前缀的情况下调用命名空间块内的任何方法——无论范围如何。

      (function() {
        namespace("example.foo", bar);
      
        function foobar() { return "foobar"; };
        function bar() { return foobar(); };
      }());
      
      example.foo.bar(); // -> "foobar"
      

      【讨论】:

        【解决方案3】:

        JS 中没有命名空间,但你可以将对象分配给其他对象,例如

        x = {};
        x.y = {};
        x.y.z = function() {};
        

        【讨论】:

        • 公平地说,这些在 JS 社区中用于组织代码时通常称为“命名空间”。
        • 当然。我只是指出它们不是真正的命名空间,它们只是看起来很像。
        【解决方案4】:

        我使用bob.js framework

        bob.ns.setNs('myApp.myMethods', {
            method1: function() {
                console.log('This is method 1');
            },
        
            method2: function() {
                console.log('This is method 2');
            }
        });
        //call method1.
        myApp.myMethods.method1();
        //call method2.
        myApp.myMethods.method2();
        

        【讨论】:

          【解决方案5】:

          如您所见,在 javascript 中自动化多级命名空间声明非常简单:

          var namespace = function(str, root) {
              var chunks = str.split('.');
              if(!root)
                  root = window;
              var current = root;
              for(var i = 0; i < chunks.length; i++) {
                  if (!current.hasOwnProperty(chunks[i]))
                      current[chunks[i]] = {};
                  current = current[chunks[i]];
              }
              return current;
          };
          
          // ----- USAGE ------
          
          namespace('ivar.util.array');
          
          ivar.util.array.foo = 'bar';
          alert(ivar.util.array.foo);
          
          namespace('string', ivar.util);
          
          ivar.util.string.foo = 'baz';
          alert(ivar.util.string.foo); 
          

          试试看:http://jsfiddle.net/stamat/Kb5xY/ 博文:http://stamat.wordpress.com/2013/04/12/javascript-elegant-namespace-declaration/

          【讨论】:

            猜你喜欢
            • 2011-03-28
            • 1970-01-01
            • 2021-12-20
            • 1970-01-01
            • 2010-12-05
            • 2011-12-02
            • 2011-03-25
            • 2016-03-09
            相关资源
            最近更新 更多