CodePark/ questions / When not to use classes
START PRACTICINGPRACTICE
Backend question · Object-oriented programming › When not to use classes

What happens on the last two lines?

function createCounter() {
  let count = 0;
  return { increment() { count++; return count; } };
}
class Counter {
  count = 0;
  increment() { this.count++; return this.count; }
}
const { increment: a } = createCounter();
const { increment: b } = new Counter();
a(); console.log(a());
b();
It logs 2, then b() throws a TypeError

It logs 2, then b() throws a TypeError. The factory's increment uses the closure variable count, not this. So it works after being destructured. The class method reads this.count. Called alone, this is undefined because class code is strict.

"Both work" is tempting because the two objects look alike from outside. The difference is where the state lives: in a closure or on
this.