这是我通常的做法:
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();