Symbol.hasInstance well-known symbol is used to determine if a constructor object recognizes an object as its instance. The instanceof operator's behavior can be customized by this symbol.

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

特性属性在 Symbol.hasInstance
可写 no
可枚举 no
可配置 no

范例

Custom instanceof behavior

You could implement your custom instanceof behavior like this, for example:

class MyArray {
  static [Symbol.hasInstance](instance) {
    return Array.isArray(instance)
  }
}
console.log([] instanceof MyArray); // true
				
function MyArray() { }
Object.defineProperty(MyArray, Symbol.hasInstance, {
  value: function(instance) { return Array.isArray(instance); }
});
console.log([] instanceof MyArray); // true
				

规范

规范
ECMAScript (ECMA-262)
The definition of 'Symbol.hasInstance' in that specification.

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
Desktop Mobile Server
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet Node.js
hasInstance Chrome 50 Edge 15 Firefox 50 IE No Opera 37 Safari 10 WebView Android 50 Chrome Android 50 Firefox Android 50 Opera Android 37 Safari iOS 10 Samsung Internet Android 5.0 nodejs 6.5.0
6.5.0
6.0.0 Disabled
Disabled From version 6.0.0: this feature is behind the --harmony runtime flag.

图例

完整支持

完整支持

不支持

不支持

用户必须明确启用此特征。

用户必须明确启用此特征。

另请参阅

元数据

  • 最后修改: