[英]OOP Pattern for Shared Functionality (e.g. Logger) in JavaScript
I need recommendations for how to program common functionality into my JavaScript application. 我需要有关如何将常用功能编程到我的JavaScript应用程序中的建议。 For example, there are these classes: Main, Logger, App and Template. 例如,有以下类别:Main,Logger,App和Template。
Main creates an instance of App and Logger, then App creates an instance of Template. Main创建App和Logger的实例,然后App创建Template的实例。 Main passes a reference of itself into App's init, and App passes it's reference of Main to Template's init. Main将其自身的引用传递给App的init,而App将其Main的引用传递给Template的init。 Now, for right or wrong, Template has direct reference to the Logger instance within Main. 现在,无论是对还是错,Template都可以直接引用Main中的Logger实例。 This is the simplest, but it doesn't seem like proper OOP as any change to logger would require rep-programming every class that invokes the reference. 这是最简单的方法,但是它似乎不是适当的OOP,因为对记录器的任何更改都需要对调用该引用的每个类进行rep-program。
Alternatively, Template could receive only a reference to App, that has a method to invoke it's reference to Main, which has a method to invoke it's instance of Logger. 另外,Template可能只收到对App的引用,该引用具有一种方法可以调用它对Main的引用,Main具有可以调用Logger实例的方法。 This seems safer in terms to keeping everyone at bay, but it also means Main will be full of methods simply to access Logger and other classes it manages. 从每个人的角度来看,这似乎更安全,但这也意味着Main将会拥有很多方法来访问Logger及其管理的其他类。
Not detailed here: I'm using John Resig's Simple JavaScript Inheritance and RequireJS. 此处未详述:我正在使用John Resig的Simple JavaScript Inheritance和RequireJS。
Example 1: 范例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");
}
}
Example 2: 范例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");
}
}
I found really useful in my OOP projects with JavaScript use the Dependency Injection pattern and Event Bus pattern. 我发现使用Dependency Injection模式和Event Bus模式在使用JavaScript的OOP项目中非常有用。 It helps a lot also for the Unit Test if you decouple the logic using MVC or MVP . 如果使用MVC或MVP解耦逻辑,则对单元测试也有很大帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.