Fat arrow function (arrow function) แก้ปัญหา lexical binding ของ this มันจับ context ของ this และทำให้บรรลุเป้าหมายเดียวกันได้ เนื่องจาก arrow function ไม่มี this ของตัวเอง Syntax => แสดง fat arrow
ตัวอย่าง
$('.button1').click(function () {
setTimeout(function () {
$(this).text('demo'); // Error: this = global/window
}, 400);
});
ข้างต้น error เพราะ function() กำหนด this เป็น global object มาแก้ด้วย fat arrow function และ context ของ this:
$('.button1').click(function () {
setTimeout(() => {
$(this).text('demo'); // this = button element (lexical)
}, 400);
});
กฎ Lexical this ของ Arrow Function
- Arrow function ไม่มี this ของตัวเอง — ใช้
thisของ enclosing scope (lexical scope) - ไม่สามารถใช้
call(),apply(),bind()เปลี่ยน this ได้ - ไม่สามารถใช้เป็น constructor (
new) ได้ - ไม่มี
argumentsobject (ใช้ rest params แทน)
เมื่อไหร่ควร/ไม่ควรใช้ Arrow Function
| สถานการณ์ | แนะนำ | เหตุผล |
|---|---|---|
| Callback ใน method | ✅ ใช่ | เก็บ this ของ object |
| Event handler | ⚠️ ระวัง | this = element (ไม่ใช่ lexical) - ใช้ function ปกติหรือ bind |
| Object method | ❌ ไม่ | ต้องการ this = object |
| Constructor | ❌ ไม่ | ไม่มี prototype, ไม่ new ได้ |