gpt4 book ai didi

javascript - 冗余和继承?

转载 作者:行者123 更新时间:2023-11-30 19:04:13 24 4
gpt4 key购买 nike

我有 2 个不同的类:产品和购物车。在 Product 类中,我有一个方法可以在表格中显示我们的产品信息。

另一个类:Cart,也需要与下面相同的方法。有没有什么方法可以在不复制整个代码的情况下重用代码。**

我考虑过继承,但不确定它是否有意义。

提前致谢

    constructor(name, location, price) {
this.name = name;
this.location = location;
this.price = price;

}
// The following method should somehow be in the other class.

displayShoppingCart() {
var orderedProductsTblBody = document.getElementById("orderedProductsTblBody");


while (orderedProductsTblBody.rows.length > 0) {
orderedProductsTblBody.deleteRow(0);
}

cartTotalPrice = 0;

for (var Product in shoppingCart) {

var row = orderedProductsTblBody.insertRow();

var cellName = row.insertCell(0);
var cellLocation = row.insertCell(1);
var cellPrice = row.insertCell(2);

cellPrice.align = "right";

cellName.innerHTML = shoppingCart[Product].name;
cellLocation.innerHTML = shoppingCart[Product].location;
cellPrice.innerHTML = shoppingCart[Product].price;

cartTotalPrice += shoppingCart[Product].price;
document.getElementById("cartTotal").innerHTML = cartTotalPrice;
}
}
}

最佳答案

假设我们声明的类类似于以下内容:

class Product {
...

getProductInfo() {
// Here we create the markup we need to display one product nicely
// We will return it as a string instead of injecting into the DOM
// The benefit of doing it this way is that the caller may need to
// transform the markup in some way (say, the Cart wants to add some
// extra wrapper around it)
...
}

// Here the "eltContainer" is the DOM element where we want the product displayed -
// can be a table cell, div or any other container of your choice
displayProduct(eltContainer) {
const markup = this.getProductInfo();
eltContainer.innerHtml = markup;
}
}

class ShoppingCart {
constructor() {
this.products = [];
}

...

displayCart() {
// Here we prepare the table, clear up the rows etc.
...
for (var product in this.products) {
const productRow = ... // Create a table row
const infoCell = ... // Create the cell that will hold our product info
product.displayProduct(infoCell);
}
}
}
...

然后我们简单地重用每个产品生成的标记,不需要复制或注入(inject)代码。

希望对您有所帮助!

关于javascript - 冗余和继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59159178/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com