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

การแชร์ Methods ใน JavaScript ด้วย Prototype

การแชร์ Methods ระหว่าง Instances ทำได้โดยการกำหนด Method ไว้ที่ Constructor.prototype ทุก Instance จะเข้าถึง Method เดียวกันผ่าน Prototype Chain ประหยัด Memory

ตัวอย่างโค้ด

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Shared Methods</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>Shared Methods ใน JavaScript</h1>
  <div class="result"></div>
  <button class="Btn">คลิกที่นี่</button>
  <h3>คลิกปุ่มด้านบนเพื่อเรียก displayInfo ของ student1 และ student2</h3>
  <script>
    const resEle = document.querySelector(".result");
    
    function Student(name, age, standard) {
      this.name = name;
      this.age = age;
      this.standard = standard;
    }
    
    // Shared Method - เพิ่มที่ Prototype
    Student.prototype.displayInfo = function() {
      return `${this.name} age ${this.age} : standard :${this.standard} <br>`;
    };
    
    const student1 = new Student("Rohan", 17, 12);
    const student2 = new Student("Shawn", 16, 11);
    
    document.querySelector(".Btn").addEventListener("click", () => {
      resEle.innerHTML = student1.displayInfo();
      resEle.innerHTML += student2.displayInfo();
    });
  </script>
</body>
</html>

Prototype vs Instance Methods


function Student(name) {
  this.name = name;
  
  // Instance Method - สร้างใหม่ทุก Instance (Memory มาก)
  this.greet = function() {
    return `Hello ${this.name}`;
  };
}

// Prototype Method - แชร์ 1 Copy (Memory น้อย)
Student.prototype.greet = function() {
  return `Hello ${this.name}`;
};

// ตรวจสอบ
const s1 = new Student("A");
const s2 = new Student("B");

s1.greet === s2.greet;        // true (Prototype) / false (Instance)
s1.hasOwnProperty('greet');   // false (Prototype) / true (Instance)

ES6 Class Syntax (Equivalent)


class Student {
  constructor(name, age, standard) {
    this.name = name;
    this.age = age;
    this.standard = standard;
  }
  
  // Auto เพิ่มที่ Prototype
  displayInfo() {
    return `${this.name} age ${this.age} : standard :${this.standard}`;
  }
  
  // Static Method - ไม่อยู่ที่ Prototype
  static createDefault() {
    return new Student("Default", 18, 12);
  }
}

ผลลัพธ์

Rohan age 17 : standard :12, Shawn age 16 : standard :11