GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||
GeezerVison is showing developer.mozilla.org — Symbol.hasInstance - JavaScript | MDN Symbol.hasInstance
| ||||||||||
Property attributes of Symbol.hasInstance | |
|---|---|
| Writable | no |
| Enumerable | no |
| Configurable | no |
The instanceof operator uses the following algorithm to calculate the return value of object instanceof constructor:
constructor has a [Symbol.hasInstance]() method, then call it with object as the first argument and return the result, coerced to a boolean. Throw a TypeError if constructor is not an object, or if constructor[Symbol.hasInstance] is not one of null, undefined, or a function.constructor doesn't have a [Symbol.hasInstance]() method (constructor[Symbol.hasInstance] is null or undefined), then determine the result using the same algorithm as Function.prototype[Symbol.hasInstance](). Throw a TypeError if constructor is not a function.Because all functions inherit from Function.prototype by default, most of the time, the Function.prototype[Symbol.hasInstance]() method specifies the behavior of instanceof when the right-hand side is a function.
You could implement your custom instanceof behavior like this, for example:
class MyArray {
static [Symbol.hasInstance](instance) {
return Array.isArray(instance);
}
}
console.log([] instanceof MyArray); // true
function MyArray() {}
Object.defineProperty(MyArray, Symbol.hasInstance, {
value(instance) {
return Array.isArray(instance);
},
});
console.log([] instanceof MyArray); // true
Just in the same manner at which you can check if an object is an instance of a class using the instanceof keyword, we can also use Symbol.hasInstance for such checks.
class Animal {
constructor() {}
}
const cat = new Animal();
console.log(Animal[Symbol.hasInstance](cat)); // true
| Specification |
|---|
| ECMAScript® 2027 Language Specification # sec-symbol.hasinstance |