Arrow function (=>) là **cú pháp ngắn gọn** thay cho function expression, nhưng **không có binding riêng** cho this, arguments, super, new.target.
3 khác biệt quan trọng
1. Không có this riêng
this trong arrow function **kế thừa từ lexical scope** (chỗ định nghĩa).
this.a = 100;
let arrow = () => { this.a = 150; };
function regular() { this.a = 200; }
console.log(this.a); // 100
arrow(); console.log(this.a); // 150 (arrow thay đổi this outer)
regular(); console.log(this.a); // 150 (regular tạo this mới, nhưng đây là global context)
2. Không có arguments object
Arrow function không có arguments — dùng ...rest params thay thế.
3. Callable nhưng không Constructible
- Function declaration/expression: **constructible** (
new Fn()) VÀ **callable** (Fn()). - Arrow function: **chỉ callable** —
new arrow()→TypeError: not a constructor. - Class constructor: **chỉ constructible**.
Khi nào dùng arrow?
- Callback ngắn:
arr.map(x => x*2) - Cần preserve
this(event handler, class method). - Không dùng làm constructor, method cần
thisdynamic, hoặc cầnarguments.