JavaScript - Symbol.hasInstance Property
In JavaScript, a unique symbol called Symbol.hasInstance property enables objects to specify how they will behave when the instanceof operator is used. Symbol.hasInstance, when specified as a method on an object, it controls the behavior of instances produced with instanceof when tested against the object.
With the use of this symbol, user-defined objects can customize the behavior of the instanceof operator, giving them more freedom in deciding whether an object is an instance of a specific constructor function.
Syntax
Following is the syntax of JavaScript Symbol.hasInstance property −
[Symbol.hasInstance](Object)
Parameters
This method accepts only one parameter. The same is described below −
object − An object is one of the constructor.
Return value
This returns true if the value is in the chain of the object otherwise false.
Examples
Example 1
Let's look at the following example, where we are going to customize instanceof for custom classes.
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
class x {
static[Symbol.hasInstance](instance) {
return Array.isArray(instance);
}
}
const a = [11, 2, 33];
document.write(a instanceof x);
</script>
</body>
</html>
If we execute the above program, it will displays the text on the webpage.
Example 2
Consider the another scenario, where we are going to customize the instanceof for custom objects.
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
function examp() {}
const x = new examp();
examp[Symbol.hasInstance] = function(instance) {
return instance.constructor && instance.constructor.name === "TP";
};
document.write(x instanceof examp);
</script>
</body>
</html>
On executing the above script, it will displays a text on the webpage.
Example 3
In the following example, we are going to use the custom constructor function with Symbol.hasInstance property.
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
function examp() {}
examp[Symbol.hasInstance] = function(instance) {
return instance instanceof examp && instance.isValid();
};
const x = new examp();
document.write(x instanceof examp);
</script>
</body>
</html>
When we execute the script, it will displays a text on the webpage.
Example 4
Following is the example, where we are going to use Symbol.hasInstance with Inheritance.
<html>
<style>
body {
font-family: verdana;
color: #DE3163;
}
</style>
<body>
<script>
class x {
static[Symbol.hasInstance](instance) {
return 'dance' in instance && typeof instance.dance === 'function';
}
}
class y {
dance() {
document.write("cat is dancing");
}
}
let cat = new y();
document.write(cat instanceof x);
</script>
</body>
</html>
On executing the above script, the output window will pop up, displaying the text on the webpage.