Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

Lexical 'this' ใน JavaScript คืออะไร?

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) ได้
  • ไม่มี arguments object (ใช้ rest params แทน)

เมื่อไหร่ควร/ไม่ควรใช้ Arrow Function

สถานการณ์แนะนำเหตุผล
Callback ใน method✅ ใช่เก็บ this ของ object
Event handler⚠️ ระวังthis = element (ไม่ใช่ lexical) - ใช้ function ปกติหรือ bind
Object method❌ ไม่ต้องการ this = object
Constructor❌ ไม่ไม่มี prototype, ไม่ new ได้