ฟังก์ชันลูกศรมีการเขียนสั้นลง แต่ความแตกต่างที่แท้จริงคือใน ลักษณะการผูกมัด ไม่ใช่แค่ syntax เท่านั้น
js
const regular = function () {};
const arrow = () => {};
const short = x => x * 2; // implicit return for one expression
ฟังก์ชันลูกศรมีการเขียนสั้นลง แต่ความแตกต่างที่แท้จริงคือใน ลักษณะการผูกมัด ไม่ใช่แค่ syntax เท่านั้น
const regular = function () {};
const arrow = () => {};
const short = x => x * 2; // implicit return for one expression
1. ไม่มี this ของตัวเอง — ลูกศรจะสืบทอด this จากขอบเขตรอบด้าน นี่คือความแตกต่างที่สำคัญที่สุดและเหตุที่มันยอดเยี่ยมสำหรับ callbacks:
const timer = {
seconds: 0,
start() {
setInterval(() => this.seconds++, 1000); // ✅ `this` is timer
// a regular function here would have its own `this` (undefined) → bug
},
};
2. ไม่มีออบเจกต์ arguments — ใช้ rest parameters แทน:
const sum = (...args) => args.reduce((a, b) => a + b, 0);
3. ไม่สามารถใช้เป็น constructors — new arrow() จะโยน error และไม่มี prototype
const obj = {
name: "Ann",
greet: () => `Hi ${this.name}`, // ❌ `this` is NOT obj (it's outer scope)
greet2() { return `Hi ${this.name}`; }, // ✅ method needs dynamic `this`
};
อย่าใช้ลูกศรสำหรับ object methods (ไม่ได้ผูกมัดกับออบเจกต์) หรือเมื่อคุณต้องการ this/arguments แบบไดนามิก (event handlers ที่อาศัยการที่ this คือ element)
ใช้ลูกศรสำหรับ callbacks และฟังก์ชันสั้นๆ โดยที่การสืบทอด this คือสิ่งที่คุณต้องการ ใช้ฟังก์ชันปกติสำหรับ methods, constructors และ prototype methods
คลังคำถามสัมภาษณ์งาน IT พร้อมคำตอบโดยละเอียด — ตั้งแต่ระดับ Junior ถึง Senior
บริจาค