新しいアキュムレータを作成する
重要度: 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);