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

การเพิ่มเมธอดให้ JavaScript Prototypes

Prototype เป็นกลไกหลักของ JavaScript สำหรับการสืบทอด (Inheritance) การเพิ่มเมธอดที่ prototype ทำให้ทุกอินสแตนซ์ที่สร้างจาก Constructor นั้นเข้าถึงเมธอดได้โดยไม่ต้องสร้างใหม่ซ้ำ

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

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Add Methods to Prototype</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>เพิ่มเมธอดให้ JavaScript Prototypes</h1>
  <div class="result"></div>
  <br />
  <button class="Btn">คลิกที่นี่</button>
  <h3>คลิกปุ่มด้านบนเพื่อเรียกเมธอดของ person1 และ person2</h3>
  <script>
    const resEle = document.querySelector(".result");
    const BtnEle = document.querySelector(".Btn");
    
    function PersonConstructor(fName, lName, birthYear) {
      this.fName = fName;
      this.lName = lName;
      this.birthYear = birthYear;
    }
    
    // เพิ่มเมธอดที่ prototype
    PersonConstructor.prototype.welcome = function() {
      return "Welcome " + this.fName + " " + this.lName;
    };
    
    PersonConstructor.prototype.calcAge = function() {
      return "Your age = " + (new Date().getFullYear() - this.birthYear);
    };
    
    const person1 = new PersonConstructor("Rohan", "Sharma", 1995);
    const person2 = new PersonConstructor("Shawn", "Smith", 1992);
    
    BtnEle.addEventListener("click", () => {
      resEle.innerHTML = "person1.welcome() = " + person1.welcome() + "<br>";
      resEle.innerHTML += "person1.calcAge() = " + person1.calcAge() + "<br>";
      resEle.innerHTML += "person2.welcome() = " + person2.welcome() + "<br>";
      resEle.innerHTML += "person2.calcAge() = " + person2.calcAge() + "<br>";
    });
  </script>
</body>
</html>

แนวทางปฏิบัติที่ดี (Best Practices)

  • เพิ่มเมธอดที่ prototype ไม่ใช่ภายใน Constructor
  • ใช้ Object.getPrototypeOf(obj) ตรวจสอบ prototype chain
  • หลีกเลี่ยงการแก้ไข built-in prototypes (Array.prototype, Object.prototype)
  • พิจารณาใช้ ES6 Classes ซึ่งเป็น syntactic sugar ของ prototype pattern

ผลลัพธ์

แสดงข้อความต้อนรับและคำนวณอายุของ person1 และ person2