我正在尝试构建一个构造函数......一个简单的银行余额概述。
这是我的代码:
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/