gpt4 book ai didi

javascript - JavaScript OOP 中的循环依赖

转载 作者:行者123 更新时间:2023-11-30 05:36:30 25 4
gpt4 key购买 nike

// 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 的方法。该代码是我目前的处理方式,我将其发布以查看它是否是最佳方式...

为了授予 Task 访问权限,我只需传递 App 的整个实例,这是否有效或是否有更好的方法来实现它?上面的代码是否是执行此类操作的一般做法?

最佳答案

是的,你拥有的很好。这是一种循环依赖,但是由于 JavaScript 的动态特性,实际上没有任何问题。

您可以从 Task 引用 App 的另一种方式是单例模式或类似的东西,但这可能更难测试。

关于javascript - JavaScript OOP 中的循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23478708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com