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

Sử dụng Arrow Function làm Method trong JavaScript


Arrow function (fat arrow) giúp giảm dòng code, cú pháp =>, không cần từ khóa function. Thường dùng cho non-method function. Xem cách dùng arrow function làm method:

Ví dụ

<!DOCTYPE html>
<html>
  <body>
    <script>
      'use strict';
      var ob1 = {
        val1: 75,
        val2: 100,
        // Arrow function làm method
        x: () => document.write(this.val1, this),
        // Function expression truyền thống
        y: function() {
          document.write("<br>" + this.val1, this);
        },
        z: function() {
          document.write("<br>" + this.val2, this);
        }
      };
      ob1.x(); // this = global/window (undefined strict mode)
      ob1.y(); // this = ob1
      ob1.z(); // this = ob1
    </script>
  </body>
</html>

Kết quả & Giải thích

  • ob1.x() (arrow): this là global/window (hoặc undefined strict mode). this.val1 → undefined. Arrow function KHÔNG phù hợp làm method.
  • ob1.y(), ob1.z() (function expression): this bind đúng = ob1. In ra 75 và 100.

Tại sao Arrow Function không hợp làm Method?

Arrow function không có this riêng → lookup this trong lexical scope (scope định nghĩa object literal). Ở top-level script, lexical scope là global.

Cách đúng: Method Shorthand (ES6) hoặc Function Expression

const obj = {
  val: 42,
  // Method shorthand (ES6) - RECOMMENDED
  method() {
    console.log(this.val); // this = obj ✅
  },
  // Hoặc function expression
  method2: function() {
    console.log(this.val); // this = obj ✅
  },
  // Arrow function - WRONG for method
  badMethod: () => {
    console.log(this.val); // this = global ❌
  }
};

obj.method();   // 42
obj.method2();  // 42
obj.badMethod(); // undefined (or global.val)

Khi nào dùng Arrow Function trong Object?

  • Callback nội bộ không cần this: arr.map(x => x * 2).
  • Class field (public class fields - stage 3): class C { handler = () => { console.log(this) } } → this bound đúng instance.

Tóm tắt

Arrow function tuyệt vời cho callback, functional programming, nhưng KHÔNG dùng làm method của object literal (trừ class field). Dùng method shorthand method() {} cho object method.