Regular Function vs Arrow Function
Arrow function viết code ngắn gọn hơn. Cả hai hoạt động tương tự nhưng có khác biệt quan trọng.
Cú pháp
// Arrow
let x = (params) => { /* code */ };
// Regular
let x = function functionName(params) { /* code */ };
1. Từ khóa "this"
Arrow function không có this riêng (lexical this). Regular function có this riêng tùy cách gọi.
Ví dụ
<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>
Kết quả
NaN 156
Arrow function square dùng this từ global scope (undefined len), regular method rectangle dùng this của object num.
2. Từ khóa 'new'
Arrow function không constructible (không dùng new được), chỉ callable. Regular function vừa callable vừa constructible.
Ví dụ
<html> <body> <script> var word = function(){ document.write(JSON.stringify(arguments)); }; new word("Tutorix","Tutorialspoint"); var newword = () => { document.write(JSON.stringify(arguments)); }; new newword("Tutorix","Tutorialspoint"); // Error: newword is not a constructor </script> </body> </html>
3. Arguments object
Arrow function không có arguments object riêng (kế thừa từ scope bao quanh). Regular function có arguments.
4. Tóm tắt khác biệt
| Đặc điểm | Regular Function | Arrow Function |
|---|---|---|
| this | Dynamic (tùy call site) | Lexical (kế thừa scope cha) |
| new | Được | Không được |
| arguments | Có | Không (dùng rest params ...args) |
| prototype | Có | Không |
| super | Có (trong class) | Kế thừa từ scope cha |
| Dùng làm method | Phù hợp | Không phù hợp |
| Callback ngắn | Verbose | Ngắn gọn, hay dùng |