Symbol.hasInstance

Symbol.hasInstance 静态数据属性代表 众所周知的符号 Symbol.hasInstanceinstanceof 运算符在其右侧操作数上查找此符号,以查找用于确定构造函数对象是否将对象识别为其实例的方法。

¥The Symbol.hasInstance static data property represents the well-known symbol Symbol.hasInstance. The instanceof 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

¥Value

众所周知的符号 Symbol.hasInstance

¥The well-known symbol Symbol.hasInstance.

Property attributes of Symbol.hasInstance
Writable no
Enumerable no
Configurable no

描述

¥Description

instanceof 运算符使用以下算法来计算 object instanceof constructor 的返回值:

¥The instanceof operator uses the following algorithm to calculate the return value of object instanceof constructor:

  1. 如果 constructor[Symbol.hasInstance]() 方法,则以 object 作为第一个参数调用它并返回结果 强制为布尔值。如果 constructor 不是对象,或者 constructor[Symbol.hasInstance] 不是 nullundefined 或函数之一,则抛出 TypeError
  2. 否则,如果 constructor 没有 [Symbol.hasInstance]() 方法(constructor[Symbol.hasInstance]nullundefined),则使用与 Function.prototype[Symbol.hasInstance]() 相同的算法确定结果。如果 constructor 不是函数,则抛出 TypeError

因为默认情况下所有函数都继承自 Function.prototype,所以大多数时候,Function.prototype[Symbol.hasInstance]() 方法指定了当右侧是函数时 instanceof 的行为。

¥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.

示例

¥Examples

自定义行为实例

¥Custom instanceof behavior

你可以像这样实现自定义 instanceof 行为,例如:

¥You could implement your custom instanceof 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

就像使用 instanceof 关键字检查对象是否是类的实例一样,我们也可以使用 Symbol.hasInstance 进行此类检查。

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

js
class Animal {
  constructor() {}
}

const cat = new Animal();

console.log(Animal[Symbol.hasInstance](cat)); // true

规范

Specification
ECMAScript Language Specification
# sec-symbol.hasinstance

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看