blob: d7ec155f7c81cca12101ef399227186716675f2c (
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
---
title: Symbol.hasInstance
slug: Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance
tags:
- ECMAScript 2015
- JavaScript
- Property
- Reference
- Symbol
translation_of: Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance
---
<div>{{JSRef}}</div>
<p><span class="seoSummary"><strong><code>Symbol.hasInstance</code></strong> は、コンストラクターオブジェクトが、そのインスタンスのオブジェクトとして認識されるかどうかを決定するために使用されます。このシンボルで、{{jsxref("Operators/instanceof", "instanceof")}} 演算子の動作をカスタマイズすることができます。</span></p>
<div>{{EmbedInteractiveExample("pages/js/symbol-hasinstance.html")}}</div>
<div class="hidden">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 <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</div>
<div>{{js_property_attributes(0,0,0)}}</div>
<h2 id="Examples" name="Examples">例</h2>
<h3 id="Custom_instanceof_behavior" name="Custom_instanceof_behavior">独自のインスタンスでの動作</h3>
<p>たとえば、次のようにして <code>instanceof</code> の独自の動作を実装することができます。</p>
<pre class="brush: js notranslate">class MyArray {
static [Symbol.hasInstance](instance) {
return Array.isArray(instance)
}
}
console.log([] instanceof MyArray); // true
</pre>
<pre class="brush: js notranslate">function MyArray() { }
Object.defineProperty(MyArray, Symbol.hasInstance, {
value: function(instance) { return Array.isArray(instance); }
});
console.log([] instanceof MyArray); // true</pre>
<h3 id="Checking_the_instance_of_an_object" name="Checking_the_instance_of_an_object">オブジェクトのインスタンスを確認する</h3>
<p><code>instanceof</code> キーワードを使ってオブジェクトがクラスのインスタンスであるかどうかを確認するのと同じ方法で、<code>Symbol.hasInstance</code> を使って確認することもできます。</p>
<pre class="brush: js notranslate">class Animal {
constructor() {}
}
const cat = new Animal();
console.log(Animal[Symbol.hasInstance](cat)); // true
</pre>
<h2 id="Specifications" name="Specifications">仕様</h2>
<table class="standard-table">
<thead>
<tr>
<th scope="col">仕様書</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{SpecName('ESDraft', '#sec-symbol.hasinstance', 'Symbol.hasInstance')}}</td>
</tr>
</tbody>
</table>
<h2 id="Browser_compatibility" name="Browser_compatibility">ブラウザーの互換性</h2>
<p>{{Compat("javascript.builtins.Symbol.hasInstance")}}</p>
<h2 id="See_also" name="See_also">関連情報</h2>
<ul>
<li>{{jsxref("Operators/instanceof", "instanceof")}}</li>
</ul>
|