【发布时间】:2014-05-05 17:57:10
【问题描述】:
// Main class
function App() {
this.task = new Task(this); // pass the instance of this class to Task so
// it has access to doSomething
}
App.prototype.doSomething = function () {
alert("I do something that Task() needs to be able to do!");
};
function Task(app) {
// This class needs access to App()'s doSomething method
this.appInstance = app;
this.appInstance.doSomething(); // Great, now Task can call the method
}
var app = new App();
上述代码的目的是让 Task 访问 App 的方法之一,称为doSomething。代码是我目前的处理方式,我发布这个看看它是否是最好的方式......
要授予任务访问权限,我只需传递 App 的整个实例,这是有效的还是有更好的方法呢?上面的代码是做这样的事情的一般做法吗?
【问题讨论】:
-
你做对了。
-
为什么
App需要知道Task? -
我觉得这个例子应该大一点,才能全面分析方法。目前它足够小,可能不明显的不良做法。
-
@IonuțG.Stan 因为我已经说过了 ;) - 这是一个例子,在我的生产代码中有很多情况下子类需要访问主类中的信息
-
@TravisJ 是的,这很公平。在我的生产代码中,每个类中大约还有 10-20 个方法,但是关于继承实例的一般问题是相同的
标签: javascript oop circular-dependency