Skip to content

Instantly share code, notes, and snippets.

@kinda-neat
Last active August 3, 2021 15:59
Show Gist options
  • Save kinda-neat/ebe88bbccdbbb3e957897e4542e0bcbe to your computer and use it in GitHub Desktop.
Save kinda-neat/ebe88bbccdbbb3e957897e4542e0bcbe to your computer and use it in GitHub Desktop.
Closures are poor man's objects and vice versa
function makeCounter(initial) {
let counter = initial || 0;
return {
inc: () => { counter += 1; },
dec: () => { counter -= 1; },
reset: () => { counter = initial || 0; }
}
}
const counter1 = makeCounter();
const counter2 = makeCounter();
counter1.inc();
counter1.inc();
counter1.dec();
counter2.inc();
counter2.inc();
counter2.reset();
class Counter {
constructor(initial) {
this.initial = initial || 0;
this.counter = this.initial;
}
inc() {
this.counter += 1;
}
dec() {
this.counter += 1;
}
reset() {
this.counter = this.initial;
}
}
const counter3 = new Counter();
const counter4 = new Counter();
counter3.inc();
counter3.inc();
counter4.inc();
counter4.dec();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment