このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docsコミュニティーについてもっと知り、仲間になるにはこちらから。
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 演算子は右辺オペランドに対して、コンストラクターオブジェクトがオブジェクトをそのインスタンスとして認識するかどうかを判断する際に使用されるメソッドを、このシンボルで探します。
In this article
試してみましょう
class Array1 { static [Symbol.hasInstance](instance) { return Array.isArray(instance); }}console.log([] instanceof Array1);// 予想される結果: 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 fromFunction.prototype by default, most of the time, theFunction.prototype[Symbol.hasInstance]() method specifies the behavior ofinstanceof when the right-hand side is a function.
例
>独自のインスタンスでの動作
たとえば、次のようにしてinstanceof の独自の動作を実装することができます。
class MyArray { static [Symbol.hasInstance](instance) { return Array.isArray(instance); }}console.log([] instanceof MyArray); // truefunction 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> |