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 September 2015.

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 の返値を計算するために以下のアルゴリズムを使用します。

  1. constructor[Symbol.hasInstance]() メソッドがあった場合、object を最初のオブジェクトとして呼び出し、結果を論理値に変換して返します。constructor がオブジェクトでない場合、または constructor[Symbol.hasInstance]nullundefined、関数のいずれでもでない場合、TypeError が発生します。
  2. それ以外の場合、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 の独自の動作を実装することができます。

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(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® 2025 Language Specification
# sec-symbol.hasinstance

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
hasInstance

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

関連情報