javascript - JavaScript ES6 使用相互依赖的依赖注入类进行实例化
问题描述
仍然试图掌握依赖注入的窍门,我遇到了一个问题。我有三个类:Main,Store,Model。Store 顾名思义:存储可在其他地方访问的数据。模型从数据库中检索数据,在我的例子中是本地/Chrome 存储。我正在尝试以解耦的方式编写类,以便以后可以测试/修改它。但是,当然,我一直在Maximum call stack size exceeded
出错,因为我认为 Store 和 Model 只是不断地循环......循环依赖。什么是可能的解决方案?
store.js
export class Store { //ok there's also a config class but that's not the problem
constructor(config, model) {
this._config = config;
this._model = model;
}
//...
}
model.js
export class Model {
constructor(config, store) {
this._config = config;
this._store = store;
}
//...
}
main.js
import { Store } from './store.js'
import { Config } from './config.js'
import { Model } from './model.js'
export class Main {
constructor(config, store, model) {
this._store = store;
this._model = model;
}
//...
}
const config = new Config();
const model = new Model(config, ???);
const store = new Store(config, ???);
const main = new Main(config, model, store);
有没有解决办法,解决方法,什么?提前致谢!
解决方案
推荐阅读
- android - Proguard 剥离实现接口。在运行时导致 java.lang.IncompatibleClassChangeError
- c# - 资源字符串,从多个选项中挑选
- java - 创建工具栏时出现异常
- sql - 使用字段组的 Sql ORDER BY
- java - 这是 http://www.springframework.org/schema/util 的 Spring JAR
- math - 涉及多概率的蒙特卡罗模拟
- c++ - 在游戏上下文中更新 actor 属性
- android - 带有图像上传百分比的 Android 进度条
- typescript - 如何在 IntelliJ IDEA 中修复 TypeScript 的 Mocha 全局符号?
- r - R中一个数据帧中的模糊匹配