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

การตรวจสอบ Instance ของ Class ใน JavaScript (instanceof)

Operator instanceof ใช้ตรวจสอบว่า Object เป็น Instance ของ Class/Constructor Function ใด โดยตรวจสอบ Prototype Chain

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

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>instanceof Demo</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>ตรวจสอบ Instance ของ Class ใน JavaScript</h1>
  <div class="result"></div>
  <button class="Btn">คลิกที่นี่</button>
  <h3>คลิกปุ่มด้านบนเพื่อตรวจสอบว่า student1 เป็น Instance ของ Student หรือไม่</h3>
  <script>
    const resEle = document.querySelector(".result");
    
    function Student(name, age, standard) {
      this.name = name;
      this.age = age;
      this.standard = standard;
    }
    
    const student1 = new Student("Rohan", 18, 12);
    
    document.querySelector(".Btn").addEventListener("click", () => {
      if (student1 instanceof Student) {
        resEle.innerHTML = "student1 เป็น Instance ของ Student";
      } else {
        resEle.innerHTML = "student1 ไม่ใช่ Instance ของ Student";
      }
    });
  </script>
</body>
</html>

instanceof ทำงานอย่างไร?


// student1 instanceof Student
// ตรวจสอบ: Student.prototype อยู่ใน Prototype Chain ของ student1 หรือไม่

student1.__proto__ === Student.prototype // true (Direct)
student1.__proto__.__proto__ === Object.prototype // true
student1.__proto__.__proto__.__proto__ === null // true (End of chain)

กรณีพิเศษและข้อควรระวัง

  • Cross-frame/iframe: instanceof ล้มเหลวถ้า Object มาจาก iframe อื่น (Constructor ต่าง Instance)
  • Primitive Values: "str" instanceof String = false (แต่ new String("str") instanceof String = true)
  • Symbol.hasInstance: สามารถ Override พฤติกรรม instanceof ได้ (ES6+)

ทางเลือกอื่นสำหรับ Type Checking

Methodใช้สำหรับตัวอย่าง
typeofPrimitivestypeof "str" === "string"
Array.isArray()ArrayArray.isArray([])
Object.prototype.toString.call()Built-in TypestoString.call([]) === "[object Array]"
constructor.nameClass Namestudent1.constructor.name === "Student"

ผลลัพธ์

student1 เป็น Instance ของ Student