返回課程

建立新的計算器

重要性:5

建立一個建構函式 Calculator,它建立具有 3 個方法的物件

  • read() 提示輸入兩個值,並將它們分別儲存為物件屬性,名稱為 ab
  • sum() 傳回這些屬性的總和。
  • mul() 回傳這些屬性的乘積。

例如

let calculator = new Calculator();
calculator.read();

alert( "Sum=" + calculator.sum() );
alert( "Mul=" + calculator.mul() );

執行範例

開啟一個包含測試的沙盒。

function Calculator() {

  this.read = function() {
    this.a = +prompt('a?', 0);
    this.b = +prompt('b?', 0);
  };

  this.sum = function() {
    return this.a + this.b;
  };

  this.mul = function() {
    return this.a * this.b;
  };
}

let calculator = new Calculator();
calculator.read();

alert( "Sum=" + calculator.sum() );
alert( "Mul=" + calculator.mul() );

在沙盒中開啟包含測試的解決方案。