Regular Functions vs Arrow Functions
Arrow Function ใช้เขียนโค้ดให้กระชับ ทั้งสอง Functions Regular และ Arrow ทำงานคล้ายกันแต่มีความแตกต่างบ้าง มาดูรายละเอียดกัน
Syntax ของ Arrow Function
let x = (params) => { // code };
Syntax ของ Regular Function
let x = function functionname(params){ // code };
การใช้คีย์เวิร์ด "this"
ไม่สามารถใช้ "this" ใน Arrow Functions ได้ ในขณะที่ Regular Functions ใช้ได้โดยไม่มีปัญหา
ตัวอย่าง
ในตัวอย่างนี้ ใช้ทั้ง Regular (rectangle) และ Arrow (square) Functions ภายใน Object "num" ที่มี Properties len และ bre เป้าหมายหา Area ของ Square (len*len) ด้วย Arrow Function และ Area ของ Rectangle (len*bre) ด้วย Regular Function แต่ "this" ไม่ทำงานใน Arrow Function ค่า Area ของ Square คืนค่า NaN ในขณะที่ Regular Function ได้ Area ของ Rectangle ถูกต้อง ตาม Output
<html> <body> <script> var num = { len: 12, bre: 13, square:() => { document.write(this.len * this.len); }, rectangle(){ document.write(this.len * this.bre); } }; num.square(); document.write("</br>"); num.rectangle(); </script> </body> </html>
ผลลัพธ์
NaN 156
การใช้คีย์เวิร์ด 'new'
Arrow Functions ไม่ใช่ "Constructible" แต่เป็น "Callable" ดังนั้น "new" ไม่ทำงาน ในขณะที่ Regular Functions เป็นทั้ง "Callable" และ "Constructible" ดังนั้น "new" ทำงานได้
ตัวอย่าง
ในตัวอย่างนี้ ใช้ "new" ส่ง Arguments ให้ทั้ง Regular และ Arrow Function แต่ Arrow Function ไม่ใช่ "Constructible" จึง Error ในขณะที่ Regular Functions ได้ Output ปกติ
<html> <body> <script> var word = function(){ document.write(JSON.stringify(arguments)); /// executes '{"0":"Tutorix","1":"Tutorialspoint"}' as output }; new word("Tutorix","Tutorialspoint"); var newword = ()=> { document.write(JSON.stringify(arguments)); //executes 'newword is not a constructor' as output }; new newword("Tutorix","Tutorialspoint"); </script> </body> </html>