javascript - 构造函数风格的银行余额工具

标签 javascript function ecmascript-6 constructor

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

这是我的代码:

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
  }
}

这就是我所期望的示例。

// Example

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

它不起作用。我哪里有错误?

最佳答案

有一些错误 - 在 var account = newbankAccount(10) 中,类名称为 BankAccount

在构造函数中,您将 amount 分配给 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

关于javascript - 构造函数风格的银行余额工具,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57936008/

相关文章:

javascript - 如果对象未定义,则映射未定义

javascript - 如何通过字符串与另一个对象访问对象属性

javascript - 使用表构建的 Jquery Accordion 菜单

javascript - 自动完成更新时如何调用JS函数

javascript - 我对 shuffle 数组函数的设置和调用哪里出了问题?

javascript - 丢失对父类的引用

javascript - 将值作为数组从 html 传递到 javascript

python - 除非我手动调用,否则我无法调用我的函数之一

javascript - 使用 [...new Set()] 仅获取基于内部 Array<object.id> 的唯一值?

javascript - 在 JavaScript 中解构对象时如何绑定(bind)方法?