鍍金池/ 問(wèn)答/HTML/ 閉包問(wèn)題中函數(shù)立即執(zhí)行

閉包問(wèn)題中函數(shù)立即執(zhí)行



var Counter = (function() {
  var privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }
  return {
    increment: function() {
      changeBy(1);
    },
    decrement: function() {
      changeBy(-1);
    },
    value: function() {
      return privateCounter;
    }
  }   
})();

console.log(Counter.value()); /* logs 0 */
Counter.increment();
Counter.increment();
console.log(Counter.value()); /* logs 2 */
Counter.decrement();
console.log(Counter.value()); /* logs 1 */

請(qǐng)問(wèn)為什么Counter()要立即執(zhí)行才能運(yùn)行正確?

回答
編輯回答
柚稚

如果不立即執(zhí)行,要達(dá)到你上面代碼的效果,應(yīng)該就要這樣寫(xiě)了。 不立即執(zhí)行的話只是聲明了個(gè)函數(shù)。

var Counter = function() {
  var privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }
  return {
    increment: function() {
      changeBy(1);
    },
    decrement: function() {
      changeBy(-1);
    },
    value: function() {
      return privateCounter;
    }
  }   
}
var obj = Counter();
console.log(obj.value());
obj.increment();
obj.increment();
console.log(obj.value());
obj.decrement();
console.log(obj.value());
2018年1月10日 02:09