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

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

เหมือนกับ Methods สามารถแชร์ Properties ระหว่าง Instances ได้โดยกำหนดที่ Constructor.prototype ใช้สำหรับ Default Values หรือ Shared State

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

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

⚠️ ข้อควรระวังสำคัญ: Shadowing


Student.prototype.school = "St Marks";

const s1 = new Student("A");
const s2 = new Student("B");

console.log(s1.school); // "St Marks" (จาก Prototype)
console.log(s2.school); // "St Marks" (จาก Prototype)

// การ Assign ให้ Instance -> สร้าง Own Property (Shadowing)
s1.school = "New School";
console.log(s1.school); // "New School" (Own Property)
console.log(s2.school); // "St Marks" (ยังจาก Prototype)
console.log(Student.prototype.school); // "St Marks" (Prototype ไม่เปลี่ยน)

// ตรวจสอบ
s1.hasOwnProperty('school'); // true (หลัง Assign)
s2.hasOwnProperty('school'); // false

เมื่อไหร่ควรใช้ Shared Properties?

  • Constants/Defaults: ค่าที่เหมือนกันทุก Instance (School Name, Config)
  • Methods: ฟังก์ชันที่ Logic เหมือนกัน (เหมาะกว่า Properties)
  • ไม่เหมาะสำหรับ: Mutable State ที่แต่ละ Instance ควรมีของตัวเอง

Mutable Shared Property Pitfall


// ❌ อันตราย: Shared Mutable Object/Array
Student.prototype.hobbies = [];

const s1 = new Student("A");
const s2 = new Student("B");

s1.hobbies.push("Reading");
console.log(s2.hobbies); // ["Reading"] - เปลี่ยนร่วมกัน! 😱

// ✅ ดี: ใช้ Instance Property สำหรับ Mutable Data
function Student(name) {
  this.name = name;
  this.hobbies = []; // แต่ละ Instance มี Array ของตัวเอง
}

ผลลัพธ์

Rohan age 17 : school :St Marks School, Shawn age 16 : school :St Marks School