概述

Symbol.hasInstance 用于判断某对象是否为某构造器的实例。 因此你可以用它自定义 instanceof 操作符在某个类上的行为。

Symbol.hasInstance 属性的属性特性:
writable false
enumerable false
configurable false

示例

例如,你可以这样来自定义 MyArray 的 instanceof 行为:

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

规范

文档 状态 备注
ECMAScript 2015 (6th Edition, ECMA-262)
Symbol.hasInstance
Standard Initial definition.
ECMAScript Latest Draft (ECMA-262)
Symbol.hasInstance
Draft  

浏览器兼容性

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 51 50 (50) 未实现 ? ?
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? ? 50.0 (50) 未实现 ? ?

参考

文档标签和贡献者

此页面的贡献者: AlexChao, Hushabyme, zhouytforever, zhengwei
最后编辑者: AlexChao,