8

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

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

我更喜欢的是:

foo.showNoteDialog()

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

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

这可能吗?我该怎么做?

4

5 回答 5

9

这是我通常的做法:

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();
于 2011-10-19T16:52:19.167 回答
4

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

(function() {
  namespace("example.foo", bar);

  function foobar() { return "foobar"; };
  function bar() { return foobar(); };
}());

example.foo.bar(); // -> "foobar"
于 2011-10-19T17:03:10.263 回答
2

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

x = {};
x.y = {};
x.y.z = function() {};
于 2011-10-19T16:46:27.087 回答
1

我使用bob.js 框架来做到这一点:

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();
于 2012-11-01T17:46:44.373 回答
1

如您所见,在 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/

于 2013-04-12T13:00:19.847 回答