this ถูกตัดสินใจโดย วิธีการเรียกฟังก์ชัน ไม่ใช่ที่ที่กำหนดไว้ มีห้ากฎ:
js
obj = {
: ,
() { .; },
};
obj.();
f = obj.;
();
f.(obj);
();
this ถูกตัดสินใจโดย วิธีการเรียกฟังก์ชัน ไม่ใช่ที่ที่กำหนดไว้ มีห้ากฎ:
obj = {
: ,
() { .; },
};
obj.();
f = obj.;
();
f.(obj);
();
Arrow functions ไม่มี this ของตัวเอง — พวกมันสืบทอดมาจากขอบเขตที่ล้อมรอบในเวลาที่กำหนด นี่คือเหตุที่ arrows ใช้ได้ดีกับ callbacks:
const obj = {
items: [1, 2],
logAll() {
// ✅ arrow inherits `this` from logAll → `this` is obj
this.items.forEach(i => console.log(this.items, i));
// ❌ a regular function here would have its own `this` (undefined) → crash
// this.items.forEach(function (i) { console.log(this.items); });
},
};
การส่งผ่าน method เป็น callback สูญเสีย binding ของมัน เพราะมันถูกเรียกอย่างเรียบง่าย:
button.addEventListener("click", obj.getX); // ❌ `this` is the button
button.addEventListener("click", () => obj.getX()); // ✅ keeps obj
button.addEventListener("click", obj.getX.bind(obj)); // ✅ also fine
การเข้าใจ this ผิด ๆ เป็นข้อบกพร่อง JS ที่พบได้บ่อยที่สุด
วิธีแก้คือ arrow function หรือ .bind() เพื่อล็อก this ที่ตั้งใจไว้