sfi*_*ier 7 javascript dependency-injection es6-modules
我有一个关于使用 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)
在我看来,我绝对不喜欢我在这里写的东西。有没有更好的方法来做到这一点?
小智 2
因此,依赖项注入消除了您的案例中 ProductModule 和 CartModule 之间的紧密耦合。您应该将购物车模块注入产品模块的构造函数中。这样做将使您的代码解耦。
constructor (private cart: CartModule) {}
Run Code Online (Sandbox Code Playgroud)
假设将来您有两种类型的购物车 - 愿望清单购物车和购物车。然后,因为您在产品模块中使用了依赖项注入,所以您可以将上述任何购物车传递到该购物车中,并根据该产品模块将产品添加到该购物车中。这会导致您创建的产品模块具有可扩展性。