我有一个关于使用 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)
在我看来,我绝对不喜欢我在这里写的东西。有没有更好的方法来做到这一点?