Javascript命名空间-多个级别

Javascript Namespace - Multiple Levels

本文关键字:命名空间 Javascript      更新时间:2023-09-26

我目前正在做以下事情来给我的javascript代码一个命名空间:

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

我更喜欢的是:

foo.showNoteDialog()

是有一个多级命名空间:

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

这可能吗?我该怎么做呢?

我通常是这样做的:

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

使用此方法可以保证文件之间的安全性。如果TopLevel已经存在,你将把它赋值给变量TopLevel,如果它不存在,你将创建一个可以扩展的空对象。

所以假设你想创建一个应用程序,它存在于应用程序名称空间中,并在多个文件中扩展,你会希望文件看起来像这样:

File 1:

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

File 2:

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

文件3 (worker):

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

看一下namspace .js。它允许您使用公共和私有方法声明嵌套的名称空间。这很好,因为它允许您调用命名空间块内的任何方法而不带前缀——无论作用域如何。

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

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

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

我使用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();

在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/