Symbol.hasInstance एक वेल-नोन सिंबल है जो यह निर्धारित करता है कि कोई कंस्ट्रक्टर किसी ऑब्जेक्ट को अपना इंस्टेंस मानता है या नहीं। यह instanceof ऑपरेटर के व्यवहार को अनुकूलित करने की अनुमति देता है।
उदाहरण
<!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 प्रॉपर्टी</h1>
<div class="sample"></div>
<button class="Btn">यहां क्लिक करें</button>
<h3>ऊपर दिए गए बटन पर क्लिक करके देखें कि सिंबल 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>
आउटपुट
क्लिक करने पर परिणाम दिखाएगा:
true- क्योंकिeleArray का इंस्टेंस हैtrue- क्योंकिstrcustom कंस्ट्रक्टर का इंस्टेंस है
उन्नत उपयोग: आप Symbol.hasInstance को ओवरराइड करके कस्टम instanceof व्यवहार बना सकते हैं:
class MyClass {
static [Symbol.hasInstance](instance) {
return instance && instance.customProperty === true;
}
}
const obj = { customProperty: true };
console.log(obj instanceof MyClass); // true