Symbol.hasInstance
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2015.
Symbol.hasInstance
用于判断某对象是否为某构造器的实例。因此你可以用它自定义 instanceof
操作符在某个类上的行为。
尝试一下
class Array1 {
static [Symbol.hasInstance](instance) {
return Array.isArray(instance);
}
}
console.log([] instanceof Array1);
// Expected output: true
Symbol.hasInstance 的属性特性 | |
---|---|
可写 | 否 |
可枚举 | 否 |
可配置 | 否 |
示例
你可实现一个自定义的instanceof
行为,例如:
js
class MyArray {
static [Symbol.hasInstance](instance) {
return Array.isArray(instance);
}
}
console.log([] instanceof MyArray); // true
规范
Specification |
---|
ECMAScript® 2025 Language Specification # sec-symbol.hasinstance |
浏览器兼容性
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
hasInstance |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.