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());
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b36d3f-2b591.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b36d3f-2b591.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?