簡體   English   中英

JavaScript 班級計算器 OOP 問題

[英]JavaScript Classes Calculator OOP problem

  1. 創建一個Calculator class。
  2. 新實例化的實例應將其total屬性初始化為0
  3. 添加以下實例方法,它們都應返回實例的重新分配的total屬性: add(num) - 將num arg 添加到total b。 subtract(num) - 從total c 中減去num arg。 divide(num) - 將total除以num arg d。 multiply(num) - 將total乘以num arg
let 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM