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

Hàm mũi tên (Arrow Functions) - Hàm viết tắt trong JavaScript


Arrow function (hàm mũi tên) là cú pháp ngắn gọn (ES2015). Đặc điểm quan trọng: không có this riêng - kế thừa this từ ngữ cảnh bao quanh (lexical scoping). Điều này giải quyết vấn đề this mất đi trong callback.

Ví dụ so sánh

Hàm thông thường vs Arrow function trong phương thức đối tượng:

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Arrow Function JS</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result { font-size: 18px; font-weight: 500; color: rebeccapurple; }
  </style>
</head>
<body>
  <h1>Hàm mũi tên (Arrow Function) trong JavaScript</h1>
  <div class="result"></div>
  <button class="Btn">SO SÁNH THIS</button>
  <h3>Nhấn nút để xem sự khác biệt this giữa function thường và arrow</h3>
  <script>
    const resEle = document.querySelector(".result");
    const btn = document.querySelector(".Btn");
    // Function thường: this phụ thuộc cách gọi
    const obj = {
      name: "Rohan",
      age: 20,
      birthday() {
        function birthYear() {
          // this ở đây là window (hoặc undefined strict mode)
          this.birthYearCalc = new Date().getFullYear() - this.age; // lỗi logic
        }
        birthYear();
      }
    };
    // Arrow function: this kế thừa từ birthday()
    const obj1 = {
      name: "Shawn",
      age: 22,
      birthday() {
        const birthYear = () => {
          this.birthYearCalc = new Date().getFullYear() - this.age; // this = obj1
        };
        birthYear();
      }
    };
    btn.addEventListener("click", () => {
      obj.birthday();
      obj1.birthday();
      resEle.innerHTML = `Function thường: Birth Year = ${obj.birthYearCalc} (sai do this=window)<br>`;
      resEle.innerHTML += `Arrow function: Birth Year = ${obj1.birthYearCalc} (đúng)`;
    });
  </script>
</body>
</html>

Kết quả

Function thường tính sai năm sinh (do this trỏ ra window). Arrow function tính đúng.

Khi KHÔNG dùng arrow: Method của object, constructor, khi cần arguments, super, new.target.