【发布时间】:2012-02-03 21:00:06
【问题描述】:
我创建了一个 javascript 应用程序,其中所有代码都在一个文件中。该应用程序已经增长了很多,我认为是时候将其拆分为多个文件了,但我很难弄清楚如何做到这一点。我认为问题在于我决定如何构建应用程序,它使用以下模板:
var myApp = function(){
//there are several global variables that all of the modules use;
var global1, global2, module1, module2;
global1 = {
prop1:1
};
//There are also several functions that are shared between modules
function globalFunction(){
}
var ModuleOne = function(){
function doSomething(){
//using the global function
globalFunction();
}
return{
doSomething:doSomething
}
};
var ModuleTwo = function(){
function doSomething(){
//module 2 also needs the global function
globalFunction();
//Use the functionality in module 1
//I can refactor this part to be loosely coupled/event driven
module1.doSomething();
}
};
module1 = new ModuleOne();
module2 = new ModuleTwo();
};
即使所有模块都是松散耦合和事件驱动的,我仍然不知道如何将其拆分为多个文件,因为每个模块都依赖于共享函数/变量。有人有建议吗?
【问题讨论】:
-
说真的,像module8 这样的工具可以解决您的问题
-
看看这篇文章中的设计模式:adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth - 您可以将模块定义拆分到多个文件中,这样可以共享通用属性,也可以创建变量或方法仅对特定文件是私有的。
-
@nnnnnn 谢谢。我现在去看看。
-
@nnnnnn 感谢那篇文章。这是完美的。您应该提交带有链接的答案,以便我接受...
-
如果模块使用共享函数/变量,那么它们就不是松散耦合的。
标签: javascript oop