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 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
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
|
Legend
- Full support
- Full support
- No support
- No support
- User must explicitly enable this feature.
- User must explicitly enable this feature.