Symbol.hasInstance
Symbol.hasInstance
は、コンストラクターオブジェクトが、そのインスタンスのオブジェクトとして認識されるかどうかを決定するために使用されます。このシンボルで、instanceof
演算子の動作をカスタマイズすることができます。
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Symbol.hasInstance のプロパティ属性 |
|
---|---|
書込可能 | 不可 |
列挙可能 | 不可 |
設定可能 | 不可 |
例
独自のインスタンスでの動作
たとえば、次のようにして instanceof
の独自の動作を実装することができます。
class MyArray {
static [Symbol.hasInstance](instance) {
return Array.isArray(instance)
}
}
console.log([] instanceof MyArray); // true
function MyArray() { }
Object.defineProperty(MyArray, Symbol.hasInstance, {
value: function(instance) { return Array.isArray(instance); }
});
console.log([] instanceof MyArray); // true
オブジェクトのインスタンスを確認する
instanceof
キーワードを使ってオブジェクトがクラスのインスタンスであるかどうかを確認するのと同じ方法で、Symbol.hasInstance
を使って確認することもできます。
class Animal {
constructor() {}
}
const cat = new Animal();
console.log(Animal[Symbol.hasInstance](cat)); // true
仕様
ブラウザーの互換性
BCD tables only load in the browser