Symbol.hasInstance
Symbol.hasInstance は、コンストラクターオブジェクトが、そのインスタンスのオブジェクトとして認識されるかどうかを決定するために使用されます。このシンボルで、instanceof 演算子の動作をカスタマイズすることができます。
試してみましょう
Symbol.hasInstance のプロパティ属性 |
|
|---|---|
| 書込可能 | 不可 |
| 列挙可能 | 不可 |
| 設定可能 | 不可 |
例
独自のインスタンスでの動作
たとえば、次のようにして instanceof の独自の動作を実装することができます。
js
class MyArray {
static [Symbol.hasInstance](instance) {
return Array.isArray(instance)
}
}
console.log([] instanceof MyArray); // true
js
function MyArray() { }
Object.defineProperty(MyArray, Symbol.hasInstance, {
value: function(instance) { return Array.isArray(instance); }
});
console.log([] instanceof MyArray); // true
オブジェクトのインスタンスを確認する
instanceof キーワードを使ってオブジェクトがクラスのインスタンスであるかどうかを確認するのと同じ方法で、Symbol.hasInstance を使って確認することもできます。
js
class Animal {
constructor() {}
}
const cat = new Animal();
console.log(Animal[Symbol.hasInstance](cat)); // true
仕様
| Specification |
|---|
| ECMAScript Language Specification # sec-symbol.hasinstance |
ブラウザーの互換性
BCD tables only load in the browser