Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

closure

var counter = (function() {  //exposed function references private state (the outer function’s scope / lexical environment) after outer returns. 
 var privateCounter = 0;
 function changeBy(val)   { privateCounter += val; }
 return {  increment: function() {changeBy(1); },
           decrement: function() {changeBy(-1);},
           value: function() {return privateCounter; }
  };
})();

counter.increment(); counter.increment();
counter.decrement();
counter.value();      //  1
Source by www.freecodecamp.org #
 
PREVIOUS NEXT
Tagged: #closure
ADD COMMENT
Topic
Name
5+5 =