Advertisement
Guest User

Untitled

a guest
Aug 29th, 2016
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.64 KB | None | 0 0
  1. 'use strict';
  2.  
  3. function counter() {
  4. // counter is just a function, it must be invoked to create the closure.
  5. let total = 0;
  6. // total becomes a private variable, accessable by returned functions
  7.  
  8. return {
  9. increment() {
  10. total++;
  11. },
  12. decrement() {
  13. total--;
  14. },
  15. getTotal() {
  16. return total;
  17. }
  18. }
  19. }
  20. const calc = counter(); // assigning the return value of counter() to calc
  21. // creates the closure and this small module.
  22. calc.increment(); // adds one to total
  23. calc.getTotal(); // => 1
  24. calc.increment(); // adds one to total
  25. calc.getTotal(); // => 2
  26. calc.decrement(); // minus one to total
  27. calc.getTotal(); // => 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement