小编sfi*_*ier的帖子

ES6 模块的依赖注入

我有一个关于使用 ES6 模块时的依赖注入和最佳实践的问题,这些模块是经常创建的。

// ProductModule.js

import {CartModule} from './CartModule.js';

export class ProductModule {
    constructor() {
        this.cartModule = new CartModule();
    }

    addToCartListener() {
        $('.product-add-cart')
            .on('click', (event) => {
                this.cartModule.addToCart(46773, 1);
            })
        ;
    }      
}

// CartModule.js

import {UserModule} from './UserModule.js';
import {OtherModule} from './OtherModule.js';

export class CartModule {
    constructor() {
        this.userModule = new UserModule();
        this.otherModule = new OtherModule();
    }

    addToCart(idProduct, quantity) {
        this.userModule.function();
        this.otherModule.function();

        console.log(idProduct, quantity);

        return true;
    }      
}
Run Code Online (Sandbox Code Playgroud)

在我看来,我绝对不喜欢我在这里写的东西。有没有更好的方法来做到这一点?

javascript dependency-injection es6-modules

7
推荐指数
1
解决办法
3057
查看次数