Symbol.hasInstance
O symbol bem-conhecido Symbol.hasInstance
é usado para determinar se um objecto construtor reconhece um objecto 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
Tu podes implementar o comportamento customizado do seu instanceof
deste jeito; por exemplo:
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 | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Symbol.hasInstance' in that specification. |
Standard | Initial definition. |
ECMAScript (ECMA-262) The definition of 'Symbol.hasInstance' in that specification. |
Living Standard |
Compatibilidade com os navegadores
We're converting our compatibility data into a machine-readable JSON format.
This compatibility table still uses the old format,
because we haven't yet converted the data it contains.
Find out how you can help!
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | 51 | 50 (50) | No support | ? | ? |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | ? | ? | 50.0 (50) | No support | ? | ? |