Symbol.hasInstance

The Symbol.hasInstance well-known symbol is used to determine if a constructor object recognizes an object as its instance. The instanceof operator's behavior can be customized by this symbol.

Property attributes of Symbol.hasInstance
Writable no
Enumerable no
Configurable no

Examples

Custom instanceof behavior

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: function(instance) { return Array.isArray(instance); }
});
console.log([] instanceof MyArray); // true

Checking the instance of an object

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 also.

class Animal {
  constructor() {}
}

const cat = new Animal();

console.log(Animal[Symbol.hasInstance](cat)); // true

Specifications

Specification
ECMAScript (ECMA-262)
The definition of 'Symbol.hasInstance' in that specification.

Browser compatibility

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
hasInstanceChrome Full support 50Edge Full support 15Firefox Full support 50IE No support NoOpera Full support 37Safari Full support 10WebView Android Full support 50Chrome Android Full support 50Firefox Android Full support 50Opera Android Full support 37Safari iOS Full support 10Samsung Internet Android Full support 5.0nodejs Full support 6.5.0
Full support 6.5.0
Full support 6.0.0
Disabled
Disabled From version 6.0.0: this feature is behind the --harmony runtime flag.

Legend

Full support  
Full support
No support  
No support
User must explicitly enable this feature.
User must explicitly enable this feature.

See also