[英]JavaScript Classes Calculator OOP problem
Calculator
class。total
屬性初始化為0
。total
屬性: add(num)
- 將num
arg 添加到total
b。 subtract(num)
- 從total
c 中減去num
arg。 divide(num)
- 將total
除以num
arg d。 multiply(num)
- 將total
乘以num
arglet calculator = new Calculator();
console.log(calculator.add(50)); // => 50
console.log(calculator.subtract(35)); // => 15
console.log(calculator.multiply(10)); // => 150
console.log(calculator.divide(5)); // => 30
console.log(calculator.total) // => 30
this is what i tried
class Calculator {
constructor(total = 0,) {
this.total = total
}
add(num){
return num + this.total
}
subtract(num) {
return this.total - num
}
divide(num) {
return this.total / num
}
multiply(num) {
return this.total * num
}
}
錯誤是您沒有重新分配實例的總屬性。 您只是返回操作的結果。
您需要將實例的總屬性重新分配給操作的結果。
比如在add方法中,需要將實例的total屬性重新賦值給加法運算的結果。
為此,您可以使用賦值運算符 (=) 將加法運算的結果賦給實例的總屬性。 例如, this.total = num + this.total
。 您需要為所有方法執行此操作。
class Calculator {
constructor(total = 0,) {
this.total = total
}
add(num){
this.total = num + this.total
return this.total
}
subtract(num) {
this.total = this.total - num
return this.total
}
divide(num) {
this.total = this.total / num
return this.total
}
multiply(num) {
this.total = this.total * num
return this.total
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.