Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict';
- function counter() {
- // counter is just a function, it must be invoked to create the closure.
- let total = 0;
- // total becomes a private variable, accessable by returned functions
- return {
- increment() {
- total++;
- },
- decrement() {
- total--;
- },
- getTotal() {
- return total;
- }
- }
- }
- const calc = counter(); // assigning the return value of counter() to calc
- // creates the closure and this small module.
- calc.increment(); // adds one to total
- calc.getTotal(); // => 1
- calc.increment(); // adds one to total
- calc.getTotal(); // => 2
- calc.decrement(); // minus one to total
- calc.getTotal(); // => 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement