【问题标题】:Redundancy and inheritance?冗余和继承?
【发布时间】:2019-12-03 14:20:34
【问题描述】:

我有 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;
        }
    }
}

【问题讨论】:

  • 乔纳森,我不太明白你想重用什么。我确实同意支持组合而不是继承,并且您应该将任何公共代码隔离到一个公共抽象中(因为启动一个函数很好)。我没有看到购物车和产品之间的任何层次关系,我确实看到了购物车聚合了多个产品的组合(没有存在依赖性,我的意思是,产品可以自己存在而不包含在购物车中)。查看您的代码,您会面临 UI 演示问题,这些问题往往会将事物与您的模型混为一谈,并且更难看到关系。

标签: javascript class inheritance redundancy


【解决方案1】:

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

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);
     }
  }
}
...

那么我们只需重用每个产品生成的标记,不需要复制或注入代码。

希望有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    • 1970-01-01
    • 2023-03-11
    • 2022-11-28
    • 1970-01-01
    相关资源
    最近更新 更多