我需要关于如何将常用功能编入JavaScript应用程序的建议。例如,有这些类:主,记录器,应用程序和模板。JavaScript中的共享功能(例如记录器)的OOP模式
Main创建App和Logger的一个实例,然后App创建一个Template实例。 Main将自身的引用传递给App的init,App将它的引用传递给模板的init。现在,对于正确或错误,Template直接引用Main中的Logger实例。这是最简单的,但它看起来不像正确的OOP,因为任何更改记录器都需要对调用引用的每个类进行重新编程。
或者,模板可能只接收对App的引用,该引用具有调用其对Main的引用的方法,该方法调用Logger的实例。这样看起来比较安全,可以让每个人都处于困境,但这也意味着Main会提供很多方法来访问记录器和其他管理的类。
这里不详细说明:我使用John Resig的Simple JavaScript Inheritance和RequireJS。
例1:
var Main = {
init: function() {
this.logger = new Logger();
this.app = new App(this);
}
}
var Logger = {
debug: function(message) {
console.log(message)
}
}
var App = {
init: function(main) {
this.template = new Template(main);
}
}
var Template = {
init: function(main) {
main.logger.debug("Hello");
}
}
例2:
var Main = {
init: function() {
this.logger = new Logger();
this.app = new App(this);
}
,debug: function(message) {
this.logger.debug(message);
}
}
var Logger = {
debug: function(message) {
console.log(message);
}
}
var App = {
init: function(main) {
this.main = main;
this.template = new Template(this);
}
,debug: function(message) {
this.main.debug(message);
}
}
var Template = {
init: function(app) {
app.debug("Hello");
}
}
[堆栈溢出不是推荐引擎](http://meta.stackexchange.com/a/128562/177538) – Joseph
使用中介器,将中介器的实例传递给每个组件,并让中介器调用实际记录器,广播公司只需要传递消息和数据:this.mediator.message(“log”,{datas:datas})。这是一个简单的解决方案,因为它将允许您即时添加其他功能(this.mediator.message(“show-alert”,message)等)。 – mpm
@JosephtheDreamer这适用于产品推荐,而不是技术解决方案。我可能会用另一个词来避免混淆。 – scader