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.
O symbol bem-conhecido Symbol.hasInstance
é usado para determinar se um objeto construtor reconhece um objeto como de sua instância. O comportamento do operador instanceof
pode ser customizado por este symbol.
Property attributes of Symbol.hasInstance | |
---|---|
Writable | no |
Enumerable | no |
Configurable | no |
Exemplos
Você pode implementar o comportamento customizado do seu instanceof
deste jeito; por exemplo:
js
class MyArray {
static [Symbol.hasInstance](instance) {
return this.prototype.isPrototypeOf(instance) || Array.isArray(instance);
}
}
console.log([] instanceof MyArray); // true
console.log(new MyArray() instanceof MyArray); // true
console.log(new Image() instanceof MyArray); // false
class MySubArray extends MyArray {}
console.log(new MySubArray() instanceof MySubArray); // true
console.log(new MySubArray() instanceof MyArray); // true
console.log(new MyArray() instanceof MySubArray); // false
Especificações
Specification |
---|
ECMAScript® 2025 Language Specification # sec-symbol.hasinstance |
Compatibilidade com navegadores
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.