Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

Symbol.hasInstance

BaselineWidely available

TheSymbol.hasInstance static data property represents thewell-known symbolSymbol.hasInstance. Theinstanceof operator looks up this symbol on its right-hand operand for the method used to determine if the constructor object recognizes an object as its instance.

Try it

class Array1 {  static [Symbol.hasInstance](instance) {    return Array.isArray(instance);  }}console.log([] instanceof Array1);// Expected output: true

Value

The well-known symbolSymbol.hasInstance.

Property attributes ofSymbol.hasInstance
Writableno
Enumerableno
Configurableno

Description

Theinstanceof operator uses the following algorithm to calculate the return value ofobject instanceof constructor:

  1. Ifconstructor has a[Symbol.hasInstance]() method, then call it withobject as the first argument and return the result,coerced to a boolean. Throw aTypeError ifconstructor is not an object, or ifconstructor[Symbol.hasInstance] is not one ofnull,undefined, or a function.
  2. Otherwise, ifconstructor doesn't have a[Symbol.hasInstance]() method (constructor[Symbol.hasInstance] isnull orundefined), then determine the result using the same algorithm asFunction.prototype[Symbol.hasInstance](). Throw aTypeError ifconstructor is not a function.

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.

Examples

Custom instanceof behavior

You could implement your custominstanceof behavior like this, for example:

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

Checking the instance of an object

Just in the same manner at which you can check if an object is an instance of a class using theinstanceof keyword, we can also useSymbol.hasInstance for such checks.

js
class Animal {  constructor() {}}const cat = new Animal();console.log(Animal[Symbol.hasInstance](cat)); // true

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-symbol.hasinstance

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp