คุณสมบัติ Symbol.hasInstance ใช้ตรวจสอบว่าคอนสตรัคเตอร์รับรู้อ็อบเจ็กต์นั้นเป็นอินสแตนซ์ของมันหรือไม่
โค้ดตัวอย่างสำหรับ Symbol.hasInstance property ดังนี้ -
ตัวอย่าง
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } div { font-size: 20px; font-weight: 500; } </style> </head> <body> <h1>JavaScript Symbol.hasInstance Property</h1> <div class="sample"></div> <button class="Btn">CLICK HERE</button> <h3> คลิกที่ปุ่มข้างบนเพื่อดูว่า symbol ข้างบนเป็น instance ของ array และ custom() ตามลำดับหรือไม่ </h3> <script> let fillEle = document.querySelector(".sample"); let ele = [1, 2, 3]; function custom() {} var str = new custom(); fillEle.innerHTML += ele + "<br>" + custom + "<br>"; document.querySelector(".Btn").addEventListener("click", () => { fillEle.innerHTML += Array[Symbol.hasInstance](ele) + "<br>"; fillEle.innerHTML += custom[Symbol.hasInstance](str); }); </script> </body> </html>
ผลลัพธ์

เมื่อคลิกปุ่ม "CLICK HERE" -
