Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Khác biệt Regular Function và Arrow Function trong JavaScript

Theo MDN: Arrow function là cú pháp ngắn gọn thay cho regular function, nhưng không có binding riêng cho this, arguments, super, new.target. Không phù hợp làm method, không dùng làm constructor.

1. Không có this binding riêng

Arrow function kế thừa this từ scope bao quanh (lexical).

Ví dụ

this.a = 100;
let arrowFunc = () => { this.a = 150 };
function regFunc() { this.a = 200; }
console.log(this.a); // 100
arrowFunc(); console.log(this.a); // 150 (arrow thay đổi this global)
regFunc(); console.log(this.a); // 150 (regular function this = global trong non-strict)

Kết quả

100 150 150

Arrow function thay đổi this bên ngoài scope. Regular function tạo this riêng.

2. Arrow function không có arguments array

arguments trong regular function là array-like object chứa tất cả tham số. Arrow function không có arguments riêng, kế thừa từ scope cha. Dùng rest parameter (...args) thay thế.

3. Arrow function: callable nhưng không constructable

  • Constructable: dùng new Fn()
  • Callable: dùng Fn()
  • Function declaration/expression: cả hai
  • Arrow function/method: chỉ callable
  • Class constructor: chỉ constructable
let arrowFunc = () => {}; new arrowFunc(); // Error: arrowFunc is not a constructor

Khi nào dùng gì:

  • Arrow: callback ngắn, functional programming, không cần this/arguments
  • Regular: method object/class, constructor, cần this/arguments, event handler