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 2017年4月.
Symbol.hasInstance は静的データプロパティで、ウェルノウンシンボルである Symbol.hasInstance を表します。instanceof 演算子は右辺オペランドに対して、コンストラクターオブジェクトがオブジェクトをそのインスタンスとして認識するかどうかを判断する際に使用されるメソッドを、このシンボルで探します。
試してみましょう
class Array1 {
static [Symbol.hasInstance](instance) {
return Array.isArray(instance);
}
}
console.log([] instanceof Array1);
// Expected output: true
値
ウェルノウンシンボル Symbol.hasInstance です。
Symbol.hasInstance のプロパティ属性 | |
|---|---|
| 書込可能 | 不可 |
| 列挙可能 | 不可 |
| 設定可能 | 不可 |
解説
instanceof 演算子は、object instanceof constructor の返値を計算するために以下のアルゴリズムを使用します。
constructorに[Symbol.hasInstance]()メソッドがあった場合、objectを最初のオブジェクトとして呼び出し、結果を論理値に変換して返します。constructorがオブジェクトでない場合、またはconstructor[Symbol.hasInstance]がnull、undefined、関数のいずれでもでない場合、TypeErrorが発生します。- それ以外の場合、
constructorに[Symbol.hasInstance]()メソッドがない場合(constructor[Symbol.hasInstance]がnullまたはundefined)、Function.prototype[Symbol.hasInstance]()と同じアルゴリズムを使用して結果を決定します。constructorが関数でない場合、TypeErrorが発生します。
Because all functions inherit from Function.prototype by default, most of the time, the Function.prototype[Symbol.hasInstance]() method specifies the behavior of instanceof when the right-hand side is a function.
例
>独自のインスタンスでの動作
たとえば、次のようにして instanceof の独自の動作を実装することができます。
class MyArray {
static [Symbol.hasInstance](instance) {
return Array.isArray(instance);
}
}
console.log([] instanceof MyArray); // true
function MyArray() {}
Object.defineProperty(MyArray, Symbol.hasInstance, {
value(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
仕様書
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-symbol.hasinstance> |
ブラウザーの互換性
Loading…