Javascript命名空间 - 多级

8

我目前正在执行以下操作,为我的javascript代码添加命名空间:

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

What I would prefer is instead of:

foo.showNoteDialog()

需要具有多级命名空间:

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

这是可能的吗?我该如何做到这一点?

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

4

看一下namespace.js。它可以让你声明带有公共和私有方法的嵌套命名空间。很好用,因为它允许你在命名空间块内调用任何方法而不需要前缀--无论作用域如何。

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

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

example.foo.bar(); // -> "foobar"

2

在JavaScript中没有命名空间,但是您可以将对象赋值给其他对象,例如:

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

4
公平地说,当这些被用来组织代码时,在JS社区中通常称之为“命名空间”。 - nrabinowitz
当然。我只是指出它们不是真正的命名空间,它们只是看起来像。 - Vala

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

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/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接