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

Cách định nghĩa Method (Phương thức) trong JavaScript


Method trong JavaScript là hành động thực hiện trên object. Method là function được lưu làm giá trị của property.

Ví dụ

<!DOCTYPE html>
<html>
  <body>
    <h3 id="myDept"></h3>
    <script>
      var department = {
        deptName: "Marketing",
        deptID: 101,
        deptZone: "North",
        // Method: function làm property value
        details: function() {
          return "Department Details<br>" + 
                 "Name: " + this.deptName + " <br>" +
                 "Zone: " + this.deptZone + "<br>" +
                 "ID: " + this.deptID;
        }
      };
      document.getElementById("myDept").innerHTML = department.details();
    </script>
  </body>
</html>

Các cách định nghĩa Method (ES6+)

1. Method Shorthand (Khuyến khích)

const obj = {
  name: "Tech",
  // Ngắn gọn, rõ ràng, this bind đúng
  greet() {
    console.log(`Hello from ${this.name}`);
  }
};
obj.greet(); // "Hello from Tech"

2. Function Expression (ES5 style)

const obj = {
  name: "Tech",
  greet: function() {
    console.log(`Hello from ${this.name}`);
  }
};

3. Arrow Function (CẨN THẬN - this lexical)

const obj = {
  name: "Tech",
  // ❌ SAI cho method: this = global/window
  badGreet: () => {
    console.log(this.name); // undefined
  },
  // ✅ OK nếu dùng class field (stage 3)
  // goodGreet = () => { console.log(this.name); }
};

Method Borrowing (Mượn method)

const obj1 = {
  name: "Obj1",
  sayHi() { console.log(this.name); }
};
const obj2 = { name: "Obj2" };

obj1.sayHi.call(obj2); // "Obj2" - mượn method, bind this = obj2
obj1.sayHi.apply(obj2); // "Obj2"
const bound = obj1.sayHi.bind(obj2);
bound(); // "Obj2"

Getter & Setter (Accessor Properties)

const user = {
  firstName: "John",
  lastName: "Doe",
  // Getter - đọc như property
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  },
  // Setter - gán như property
  set fullName(value) {
    [this.firstName, this.lastName] = value.split(" ");
  }
};

console.log(user.fullName); // "John Doe" (gọi getter)
user.fullName = "Jane Smith"; // gọi setter
console.log(user.firstName); // "Jane"

Tóm tắt

  • Method = Function property của object.
  • Dùng Method Shorthand method() {} (ES6) - clean, this đúng.
  • Arrow function KHÔNG dùng làm method object literal (this sai).
  • Getter/Setter cho computed property.
  • call, apply, bind kiểm soát this.