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 TypeErrorIt 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.
Read more