blob: 95b8c11f5979d0d7b2a2a2a14dd60d99a9173515 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
---
title: Symbol.hasInstance
slug: Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance
translation_of: Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance
---
<p>{{JSRef}}</p>
<p><strong><code>Symbol.hasInstance</code></strong>用于判断某对象是否为某构造器的实例。因此你可以用它自定义 {{jsxref("Operators/instanceof", "instanceof")}} 操作符在某个类上的行为。</p>
<div>
<div>{{EmbedInteractiveExample("pages/js/symbol-hasinstance.html")}}</div>
<div>{{js_property_attributes(0,0,0)}}</div>
<h2 id="示例">示例</h2>
<p>你可实现一个自定义的<code>instanceof</code> 行为,例如:</p>
<pre class="brush: js">class MyArray {
static [Symbol.hasInstance](instance) {
return Array.isArray(instance);
}
}
console.log([] instanceof MyArray); // true</pre>
<h2 id="规范">规范</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">文档</th>
<th scope="col">状态</th>
<th scope="col">备注</th>
</tr>
<tr>
<td>{{SpecName('ES6', '#sec-symbol.hasinstance', 'Symbol.hasInstance')}}</td>
<td>{{Spec2('ES6')}}</td>
<td>Initial definition.</td>
</tr>
<tr>
<td>{{SpecName('ESDraft', '#sec-symbol.hasinstance', 'Symbol.hasInstance')}}</td>
<td>{{Spec2('ESDraft')}}</td>
<td></td>
</tr>
</tbody>
</table>
<h2 id="浏览器兼容性">浏览器兼容性</h2>
<p>{{Compat("javascript.builtins.Symbol.hasInstance")}}</p>
<h2 id="参见">参见</h2>
<ul>
<li>{{jsxref("Operators/instanceof", "instanceof")}}</li>
</ul>
|