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

Khi NÀO KHÔNG nên dùng Arrow Function trong JavaScript


KHÔNG dùng arrow function cho:

  1. Method của object: Arrow function không có this riêng -> this trỏ ra window (hoặc undefined strict mode).
  2. Constructor: Không thể dùng new với arrow function.
  3. Cần arguments, super, new.target: Arrow function không có các binding này.
  4. Event handler cần this = element: Dùng function thường hoặc bind.

Ví dụ sai

Dùng arrow function làm method add của object -> this.a undefined:

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>When not to use arrow</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result { font-size: 20px; font-weight: 500; color: blueviolet; }
  </style>
</head>
<body>
  <h1>Khi KHÔNG nên dùng Arrow Function</h1>
  <br />
  <div class="result"></div>
  <br />
  <button class="Btn">GỌI METHOD</button>
  <h3>Nhấn nút để gọi obj.add() - arrow function method (sai)</h3>
  <script>
    const btn = document.querySelector('.Btn');
    const resEle = document.querySelector('.result');
    const obj = {
      a: 22,
      b: 44,
      // SAI: arrow function không có this của obj
      add: () => {
        return this.a + this.b; // this = window -> NaN
      }
    };
    btn.addEventListener('click', () => {
      resEle.textContent = `Tổng ${obj.a} + ${obj.b} = ${obj.add()}`; // NaN
    });
  </script>
</body>
</html>

Kết quả

Hiển thị: Tổng 22 + 44 = NaN (vì this.a, this.b là undefined trên window).

Sửa đúng: Dùng method shorthand add() { return this.a + this.b; } hoặc function expression add: function() {...}.