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
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
hasInstance Chrome Full support 50 Edge Full support 15 Firefox Full support 50 IE No support No Opera Full support Yes Safari Full support Yes WebView Android Full support 50 Chrome Android Full support 50 Firefox Android Full support 50 Opera Android Full support Yes Safari iOS Full support Yes Samsung Internet Android Full support 5.0 nodejs 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.

参见