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
79
80
81
|
---
title: Symbol.hasInstance
slug: Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance
tags:
- ECMAScript 2015
- JavaScript
- 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="Приклади">Приклади</h2>
<h3 id="Змінена_поведінка_instanceof">Змінена поведінка instanceof</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="Перевіряємо_екземпляр_обєкта">Перевіряємо екземпляр об'єкта</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="Специфікації">Специфікації</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="Сумісність_з_веб-переглядачами">Сумісність з веб-переглядачами</h2>
<p>{{Compat("javascript.builtins.Symbol.hasInstance")}}</p>
<h2 id="Див._також">Див. також</h2>
<ul>
<li>{{jsxref("Operators/instanceof", "instanceof")}}</li>
</ul>
|