A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance below:

Symbol.hasInstance - JavaScript | MDN

Symbol.hasInstance

Baseline Widely available

Symbol.hasInstance は静的データプロパティで、ウェルノウンシンボルである Symbol.hasInstance を表します。instanceof 演算子は右辺オペランドに対して、コンストラクターオブジェクトがオブジェクトをそのインスタンスとして認識するかどうかを判断する際に使用されるメソッドを、このシンボルで探します。

試してみましょう
class Array1 {
  static [Symbol.hasInstance](instance) {
    return Array.isArray(instance);
  }
}

console.log([] instanceof Array1);
// Expected output: true
値

ウェルノウンシンボル Symbol.hasInstance です。

書込可能 不可 列挙可能 不可 設定可能 不可 解説

instanceof 演算子は、object instanceof constructor の返値を計算するために以下のアルゴリズムを使用します。

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

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
仕様書 ブラウザーの互換性 関連情報

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4