私たちはこのオープンソースプロジェクトを世界中の人々に提供したいと考えています。このチュートリアルの内容をあなたが知っている言語に翻訳するのを手伝ってください。
レッスンに戻る

新しい Accumulator を作る

重要性: 5

コンストラクタ関数 Accumulator(startingValue) を作りなさい。

作成するオブジェクトは:

  • “現在の値” をプロパティ value に格納します。開始値はコンストラクタ startingValue の引数がセットされます。
  • read() メソッドは prompt を使って新しい値を読み込み、value に加算します。

つまり、value プロパティーはユーザーが入力したすべての値と初期値 startingValue の合計です。

これはそのコードのデモです:

let accumulator = new Accumulator(1); // 初期値 1 accumulator.read(); // ユーザの入力値の加算 accumulator.read(); // ユーザの入力値の加算 alert(accumulator.value); // それらの値の合計を表示

デモを実行

テストと一緒にサンドボックスを開く

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

サンドボックスでテストと一緒に解答を開く