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

การแชร์เมธอดระหว่างออบเจกต์ในอาร์เรย์ด้วย Prototype ใน JavaScript

ใน JavaScript สามารถแชร์เมธอดระหว่างอินสแตนซ์หลายตัวได้โดยการกำหนดเมธอดไว้ที่ prototype ของ Constructor Function ทำให้ประหยัดหน่วยความจำ เพราะไม่ต้องสร้างเมธอดใหม่ทุกครั้งที่สร้างออบเจกต์

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

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Shared Method via Prototype</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>แชร์เมธอดระหว่างออบเจกต์ในอาร์เรย์</h1>
  <div class="result"></div>
  <button class="Btn">คลิกที่นี่</button>
  <h3>คลิกปุ่มด้านบนเพื่อเรียกเมธอด welcome() ของออบเจกต์ person ทั้งหมด</h3>
  <script>
    const resEle = document.querySelector(".result");
    
    function Person(firstName, lastName) {
      this.firstName = firstName;
      this.lastName = lastName;
    }
    
    // เพิ่มเมธอดที่ prototype - จะถูกแชร์ให้ทุกอินสแตนซ์
    Person.prototype.welcome = function() {
      return "Welcome " + this.firstName + " " + this.lastName;
    };
    
    const persons = [
      new Person("Rohit", "Sharma"),
      new Person("Shawn", "Mendes"),
      new Person("Michael", "Clarke")
    ];
    
    document.querySelector(".Btn").addEventListener("click", () => {
      persons.forEach(person => {
        resEle.innerHTML += person.welcome() + "<br>";
      });
    });
  </script>
</body>
</html>

ประโยชน์ของ Prototype

  • ประหยัดหน่วยความจำ: เมธอดมีเพียงหนึ่งเดียวในหน่วยความจำ แทนที่จะสร้างใหม่ทุกอินสแตนซ์
  • การอัปเดตง่าย: เปลี่ยนเมธอดที่ prototype ครั้งเดียว ทุกอินสแตนซ์จะได้รับการเปลี่ยนแปลง
  • สืบทอดได้: คลาสลูกสามารถสืบทอดเมธอดจาก prototype ของคลาสแม่

ผลลัพธ์

แสดงข้อความต้อนรับสำหรับแต่ละบุคคลในอาร์เรย์