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

Static Properties ใน JavaScript

Static Properties เป็น Properties ที่ผูกติดกับ Class/Constructor Function ตัวเอง ไม่ใช่ Instance เรียกใช้ได้โดยไม่ต้องสร้าง Object (No Instantiation Required)

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

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Static 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>Static Properties ใน JavaScript</h1>
  <div class="result"></div>
  <button class="Btn">คลิกที่นี่</button>
  <h3>คลิกปุ่มด้านบนเพื่อเข้าถึง Static Property school ของ Student</h3>
  <script>
    const resEle = document.querySelector(".result");
    
    function Student(name, age) {
      this.name = name;
      this.age = age;
    }
    
    // Static Property - ผูกกับ Function ตัวเอง
    Student.school = "St Marks Public School";
    
    document.querySelector(".Btn").addEventListener("click", () => {
      resEle.innerHTML = `Student.school = ${Student.school}`;
    });
  </script>
</body>
</html>

Static Properties vs Instance Properties

ด้านStatic PropertyInstance Property
เข้าถึงผ่านClassName.propinstance.prop
เก็บที่Constructor FunctionInstance Object
Shared?✅ แชร์ร่วมกันทุก Instance❌ แยก Instance
Memory1 CopyN Copies
this contextClass (Static Method)Instance

ES6 Class Syntax (Modern)


class Student {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  // Static Property (ES2022+)
  static school = "St Marks Public School";
  
  // Static Method
  static getSchool() {
    return this.school; // this = Student Class
  }
  
  // Instance Method
  getInfo() {
    return `${this.name}, ${this.age}, ${Student.school}`;
  }
}

console.log(Student.school);        // "St Marks Public School"
console.log(Student.getSchool());   // "St Marks Public School"

const s1 = new Student("John", 20);
console.log(s1.getInfo());          // "John, 20, St Marks Public School"
// console.log(s1.school);          // undefined! ไม่เข้าถึงได้จาก Instance

Use Cases

  • Configuration/Constants: Config.API_URL
  • Factory Methods: User.fromJSON(json)
  • Counters/Registry: User.instanceCount
  • Utility Methods: Math.PI, Math.random()

ผลลัพธ์

Student.school = St Marks Public School