用相互依赖的依赖项注入类实例化JavaScript ES6

时间:2019-11-15 01:24:08

标签: javascript ecmascript-6 es6-modules es6-class

仍然试图摆脱依赖注入的困扰,但我遇到了一个问题。我有三个类:Main,Store,Model。顾名思义,存储的作用是:存储可在其他位置访问的数据。模型从数据库(在我的情况下是本地/ 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);

是否有解决方法,解决方法?预先感谢!

0 个答案:

没有答案
相关问题