【问题标题】:Constructor function style bank balance tool构造函数式银行余额工具
【发布时间】:2019-09-14 13:34:08
【问题描述】:

我正在尝试构建一个构造函数...一个简单的银行余额概览。

这是我的代码:

class BankAccount {
  constructor(amount = 0) {
    this.toal = amount;
  }
  balance(amount) {
    return this.amount
  }

  withdraw(amount) {
    this.amount - amount;
    return this.amount
  }

  deposit(amount) {
    this.amount + amount;
    return this.amount
  }
}

这是我期望的例子。

// 示例

var account = new bankAccount(10)
account.withdraw(2)
account.withdraw(5)
account.deposit(4)
account.deposit(1)
account.balance() // 8

它不起作用。我哪里错了?

【问题讨论】:

  • this.amount-amount; 等...不会更改金额的值,您需要自己通过重新分配来更新它(this.amount = this.amount-amount;
  • 也是新的 BankAccount,而不是您代码中的 bankAccount

标签: javascript function ecmascript-6 constructor


【解决方案1】:

有一些错误- 在var account = new bankAccount(10) 中,类名是BankAccount

在构造函数中,您将数量分配给this.total,然后您使用this.amount,它不是类成员。而是将其分配给this.amount

平衡方法不需要参数balance(amount) --> balance().

withdraw方法中,你是在扣除参数传递量,但最终结果应该存储在this.amount中。 this.amount = this.amount - amount;。与deposit 方法类似。

class BankAccount {
  constructor(amount = 0) {
    this.amount = amount;
  }
  balance() {
    return this.amount
  }

  withdraw(amount) {
    this.amount = this.amount - amount;
    return this.amount
  }

  deposit(amount) {
    this.amount = this.amount + amount;
    return this.amount
  }
}

var account = new BankAccount(10)
account.withdraw(2)
account.withdraw(5)
account.deposit(4)
account.deposit(1)
console.log(account.balance()) // 8

【讨论】:

    【解决方案2】:

    您没有设置this.amount。你应该这样做:

    this.amount = this.amount-amount;
    

    this.amount = this.amount+amount;
    

    否则金额始终相同

    【讨论】:

      【解决方案3】:

      你需要给amount赋值表达式的返回值,如下:

      (注意total 中的拼写错误)

      class BankAccount {
          constructor (amount = 0) {
              this.total = amount;
          }
          balance(amount) {
              return this.amount
          }
      
          withdraw (amount) {
              this.amount = this.amount - amount;
              return this.amount
          }
      
          deposit(amount) {
              this.amount = this.amount + amount;
              return this.amount
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2021-07-05
        • 1970-01-01
        • 1970-01-01
        • 2015-08-31
        • 2012-08-30
        • 2015-02-18
        • 2018-01-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多