首页 > 解决方案 > JavaScript ES6 税收计算,某些项目免税

问题描述

我正在设置一个 es6/oop 税收计算器,但在正确设置税额时遇到了一些问题。我正在用它们的数量和价格实例化产品对象并将它们添加到库存中,然后在整个库存上调用一个总方法。有些产品是免税的,所以我使用的是 BasicProduct 对象和 ExemptProduct 对象:

const Product = require('./Product')

class ExemptProduct extends Product {
  constructor(product) {
    super(product)

    this._salesTax = product.salesTax
  }

  get salesTax() {
    return this.setSalesTax();
  }

  setSalesTax () {
    return null;
  }
}

module.exports = ExemptProduct

BasicObject 将销售税设置为 0.10。我的total方法在这里:

total() {
    let total = 0
    let tax = 0
    let importDuty = .05

    for (let productId in this.items) {
        total += this.inventory.products.find(product => {
            return product.id == productId
        }).price * this.items[productId]

        tax += this.inventory.products.find(product => {
            return product.id == productId
        }).salesTax * this.items[productId]

        console.log(tax)
    }

    let taxToApply = total * tax
    let importDutyToApply = total * importDuty
    total = total + taxToApply + importDutyToApply

    return total
}

现在我正在测试三个库存项目,其中两个实例化为免税产品。他们都以正确的税额注销,直到达到此为止for in。我留在那里的console.log 打印出所有三个的0.10,而其中两个应该是0/null。我试图避免对每个项目的税额进行硬编码,因为最终只有两种税种。

标签: javascriptoopobjectecmascript-6

解决方案


推荐阅读