レッスンに戻る

カウンターオブジェクト

重要度:5

ここで、コンストラクタ関数を使用してカウンターオブジェクトが作成されます。

これは機能しますか?何が表示されますか?

function Counter() {
  let count = 0;

  this.up = function() {
    return ++count;
  };
  this.down = function() {
    return --count;
  };
}

let counter = new Counter();

alert( counter.up() ); // ?
alert( counter.up() ); // ?
alert( counter.down() ); // ?

確かに、問題なく機能します。

ネストされた両方の関数は、同じ外部字句環境内で作成されるため、同じcount変数へのアクセスを共有します。

function Counter() {
  let count = 0;

  this.up = function() {
    return ++count;
  };

  this.down = function() {
    return --count;
  };
}

let counter = new Counter();

alert( counter.up() ); // 1
alert( counter.up() ); // 2
alert( counter.down() ); // 1