Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีกำหนด Method ใน JavaScript

Method ใน JavaScript คือ action ที่ทำงานบน objects Method มี function definition ที่เก็บเป็น property value

ตัวอย่าง

<!DOCTYPE html> 
<html> 
  <body> 
    <h3 id="myDept"></h3> 
    <script> 
      var department = { 
        deptName: "Marketing", 
        deptID: 101, 
        deptZone: "North", 
        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>

วิธีประกาศ Method แบบต่างๆ (ES6+)

// 1. Method shorthand (แนะนำ - สั้นกว่า)
const obj = {
  name: "John",
  greet() {           // ไม่ต้องเขียน function
    console.log(`Hello, ${this.name}`);
  }
};

// 2. Property with function expression
const obj2 = {
  name: "John",
  greet: function() {  // ต้องเขียน function
    console.log(`Hello, ${this.name}`);
  }
};

// 3. Arrow function property (⚠️ this เป็น lexical)
const obj3 = {
  name: "John",
  greet: () => console.log(`Hello, ${this.name}`)  // this = global/undefined
};

// 4. Dynamic method names (computed property names)
const methodName = 'sayHi';
const obj4 = {
  [methodName]() { console.log('Hi!'); }
};
obj4.sayHi();  // "Hi!"

Method vs Function

  • Function: standalone block of code
  • Method: function ที่เป็น property ของ object — เข้าถึง this ได้