首页 > 解决方案 > 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);

有没有解决办法,解决方法,什么?提前致谢!

标签: javascriptecmascript-6es6-moduleses6-class

解决方案


推荐阅读