レッスンに戻る

新しい計算機を作成

重要度: 5

次の3つのメソッドを持つオブジェクトを作成するコンストラクタ関数計算機を作成してください。

  • 読み取り()は2つの値を求め、それらをオブジェクトのプロパティにそれぞれabの名前で保存します。
  • 合計()はこれらのプロパティの合計を返します。
  • 乗算()はこれらのプロパティの乗算結果を返します。

例えば

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() );

サンドボックスでテスト付きの解決策を開きます。