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

Arrow Functions ใน JavaScript

ตาม MDN Arrow function expression เป็น syntactically compact alternative ของ regular function expression แต่ไม่มี bindings ของ this, arguments, super, new.target เอง Arrow functions ไม่เหมาะเป็น methods และไม่สามารถใช้เป็น constructors ได้

มี 3 ความแตกต่างเล็กน้อยระหว่าง regular functions และ arrow functions

  • No own this binding

    Arrow functions ไม่มี this ของตัวเอง this ภายใน arrow function จะ inherited จาก 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 แค่เปลี่ยนภายในตัวเอง

  • Arrow functions ไม่มี arguments array ใน JS arguments array ในฟังก์ชันเป็น special object ใช้ดึง arguments ทั้งหมดที่ส่งมา คล้าย this arrow functions ไม่มี binding ของ arguments object ของตัวเอง ผูกกับ arguments ของ enclosing scope

  • Arrow functions เรียกได้แต่สร้างไม่ได้ (callable but not constructible) ถ้าฟังก์ชัน constructible เรียกด้วย new ได้ (new User()) ถ้า callable เรียกโดยไม่มี new ได้ (normal call)

    Functions จาก declarations/expressions เป็นทั้ง constructible และ callable

    Arrow functions (และ methods) เรียกได้อย่างเดียว class constructors สร้างได้อย่างเดียว

    พยายาม call non-callable หรือ construct non-constructible จะได้ runtime error

ตัวอย่าง

let arrowFunc = () => {} new arrowFunc()

ผลลัพธ์

arrowFunc is not a constructor