The function is executed immediately in the closure problem.



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 */

Why does Counter () need to be executed immediately to run correctly?

Mar.06,2021

if you don't execute it immediately, you should write it this way to achieve the effect of your code above. If you don't execute it immediately, you just declare a function.

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