我目前正在执行以下操作来为我的 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 变量,如果不存在,您将创建一个可以扩展的空对象。
因此,假设您要创建一个存在于 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( worker ):
//call the functions (note you could also check for their existence first here)
Application.CoreFunctionality.Function1();
Application.OtherFunctionality.Function1();
关于Javascript 命名空间 - 多层次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7824876/