レッスンに戻る

新しいアキュムレータを作成する

重要度: 5

コンストラクタ関数Accumulator(startingValue)を作成します。

作成されるオブジェクトは

  • valueプロパティに「現在の値」を格納する必要があります。開始値は、コンストラクタstartingValueの引数に設定されます。
  • read()メソッドはpromptを使用して新しい数値を読み取り、valueに追加する必要があります。

言い換えると、valueプロパティは初期値startingValueを持つユーザー入力値の合計です。

コードのデモは次のとおりです。

let accumulator = new Accumulator(1); // initial value 1

accumulator.read(); // adds the user-entered value
accumulator.read(); // adds the user-entered value

alert(accumulator.value); // shows the sum of these values

デモを実行する

テスト付きサンドボックスを開く。

function Accumulator(startingValue) {
  this.value = startingValue;

  this.read = function() {
    this.value += +prompt('How much to add?', 0);
  };

}

let accumulator = new Accumulator(1);
accumulator.read();
accumulator.read();
alert(accumulator.value);

テスト付きの課題をサンドボックスで開く。