返回課程

計數器物件

重要性: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