ตาม MDN Arrow Function Expression เป็น Syntactically Compact Alternative ของ Regular Function Expression แต่ไม่มี Bindings ของ this, arguments, super, new.target เอง Arrow Functions ไม่เหมาะเป็น Methods และไม่สามารถใช้เป็น Constructors ได้
มี 3 ความแตกต่างที่ละเอียดระหว่าง Regular และ Arrow Functions
ไม่มี This Bindings ของตัวเอง
Arrow Functions ไม่มี this Value ของตัวเอง ค่า this ภายใน Arrow Function จะสืบทอดจาก Enclosing Scope เสมอ
ตัวอย่าง
this.a = 100; let arrowFunc = () => {this.a = 150}; function regFunc() { this.a = 200; } console.log(this.a) arrowFunc() console.log(this.a) regFunc() console.log(this.a)
ผลลัพธ์
100 150 150
เห็นว่า Arrow Function เปลี่ยน this Object นอก Scope Regular Function แค่เปลี่ยนภายใน this ของตัวเอง
Arrow Functions ไม่มี Arguments Array
ใน JS Arguments Array ใน Functions เป็น Special Object ใช้ดึง Arguments ทั้งหมดที่ส่งมา คล้ายกับ this Arrow Functions ไม่มี Binding ของ Arguments Object ของตัวเอง ผูกกับ Arguments ของ Enclosing Scope
Arrow Functions เรียกได้ (Callable) แต่สร้างไม่ได้ (Not Constructable)
ถ้า Function เป็น Constructable เรียกด้วย new ได้ (new User()) ถ้า Callable เรียกโดยไม่มี new ได้ (Normal Function Call)
Functions จาก Declarations/Expressions เป็นทั้ง Constructable และ Callable
Arrow Functions (และ Methods) เป็น Callable เท่านั้น Class Constructors เป็น Constructable เท่านั้น
พยายาม Call Non-callable หรือ Construct Non-constructable จะได้ Runtime Error
let arrowFunc = () => {} new arrowFunc() This code gives the error: arrowFunc is not a constructor