Symbol.hasInstance

Symbol.hasInstance用于判断某对象是否为某构造器的实例。因此你可以用它自定义 instanceof 操作符在某个类上的行为。

Symbol.hasInstance 属性的属性特性:
writable false
enumerable false
configurable false

示例

你可实现一个自定义的instanceof 行为,例如:

class MyArray {  
  static [Symbol.hasInstance](instance) {
    return Array.isArray(instance);
  }
}
console.log([] instanceof MyArray); // true

规范

文档 状态 备注
ECMAScript 2015 (6th Edition, ECMA-262)
Symbol.hasInstance
Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)
Symbol.hasInstance
Draft

浏览器兼容性

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 YesSafari Full support YesWebView Android Full support 50Chrome Android Full support 50Firefox Android Full support 50Opera Android Full support YesSafari iOS Full support YesSamsung Internet Android Full support Yesnodejs 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.

参见