Trong class, this trong constructor và methods trỏ đến instance được tạo.
Tuy nhiên, khi truyền method như callback, mất this binding.
javascript
class Counter {
count = 0;
// Class field arrow: auto-binds this
increment = () => { this.count++; };
}
const c = new Counter();
const { increment } = c; // destructure method
increment(); // OK — this vẫn là Counter instance
console.log(c.count); // 1Giải pháp: dùng arrow function trong class fields (tự bind), bind trong constructor, hoặc .bind() khi truyền callback.
In a class, this inside the constructor and methods points to the created instance.
However, when passing a method as a callback, the this binding is lost.
javascript
class Counter {
count = 0;
// Class field arrow: auto-binds this
increment = () => { this.count++; };
}
const c = new Counter();
const { increment } = c; // destructure method
increment(); // OK — this still refers to Counter instance
console.log(c.count); // 1Solutions: use arrow functions in class fields (auto-bind), bind in the constructor, or use .bind() when passing callbacks.