Emulating private methods with closures

Emulating private methods with closures

  JavaScript does not provide a native way of doing this, but it is possible to emulate private methods using closures. Private methods aren't just useful for restricting access to code: they also provide a powerful way of managing your global namespace, keeping non-essential methods from cluttering up the public interface to your code.

  The following code illustrates how to use closures to define public functions that can access private functions and variables. 

  

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
View Code

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

原文地址:https://www.cnblogs.com/tekkaman/p/6610299.html