Cơ BảnJavaScript iconJavaScript

this trong class JavaScript là gì?

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); // 1

Giải pháp: dùng arrow function trong class fields (tự bind), bind trong constructor, hoặc .bind() khi truyền callback.

Xem toàn bộ JavaScript cùng filter theo level & chủ đề con.

Mở danh sách JavaScript