You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The`instanceof`operator allows to check whether an object belongs to a certain class. It also takes inheritance into account.
3
+
Оператор`instanceof`дозволяє перевірити, чи належить об’єкт до певного класу. Він також враховує наслідування.
4
4
5
-
Such a check may be necessary in many cases. For example, it can be used for building a *polymorphic* function, the one that treats arguments differently depending on their type.
5
+
Така перевірка може знадобитися в багатьох випадках. Наприклад, його можна використати для створення *поліморфної* функції, яка обробляє аргументи по-різному залежно від їх типу.
6
6
7
-
## The instanceof operator[#ref-instanceof]
7
+
## Оператор instanceof [#ref-instanceof]
8
8
9
-
The syntax is:
9
+
Синтаксис такий:
10
10
```js
11
11
obj instanceof Class
12
12
```
13
13
14
-
It returns`true` if`obj`belongs to the`Class`or a class inheriting from it.
14
+
Він повертає`true`, якщо`obj`належить до класу`Class`або класу, який наслідується від нього.
15
15
16
-
For instance:
16
+
Наприклад:
17
17
18
18
```js run
19
19
classRabbit {}
20
20
let rabbit =newRabbit();
21
21
22
-
//is it an object of Rabbit class?
22
+
//Чи це об’єкт класу Rabbit?
23
23
*!*
24
24
alert( rabbit instanceof Rabbit ); // true
25
25
*/!*
26
26
```
27
27
28
-
It also works with constructor functions:
28
+
Він також працює з функціями-конструкторами:
29
29
30
30
```js run
31
31
*!*
32
-
//instead of class
32
+
//замість класу
33
33
functionRabbit() {}
34
34
*/!*
35
35
36
36
alert( newRabbit() instanceof Rabbit ); // true
37
37
```
38
38
39
-
...And with built-in classes like`Array`:
39
+
...І з вбудованими класами як`Array`:
40
40
41
41
```js run
42
42
let arr = [1, 2, 3];
43
43
alert( arr instanceofArray ); // true
44
44
alert( arr instanceofObject ); // true
45
45
```
46
46
47
-
Please note that `arr`also belongs to the`Object` class. That's because `Array`prototypically inherits from`Object`.
47
+
Будь ласка, зверніть увагу, що `arr`також належить до класу`Object`. Це тому, що клас `Array`прототипно наслідується від`Object`.
48
48
49
-
Normally, `instanceof`examines the prototype chain for the check. We can also set a custom logic in the static method `Symbol.hasInstance`.
49
+
Зазвичай, `instanceof`перевіряє ланцюжок прототипів. Ми також можемо задати будь-яку спеціальну логіку в статичному методі `Symbol.hasInstance`, і замінити звичайну поведінку.
50
50
51
-
The algorithm of `obj instanceof Class`works roughly as follows:
51
+
Алгоритм операції `obj instanceof Class`працює приблизно наступним чином:
52
52
53
-
1.If there's a static method `Symbol.hasInstance`, then just call it: `Class[Symbol.hasInstance](obj)`. It should return either `true`or`false`, and we're done. That's how we can customize the behavior of`instanceof`.
53
+
1.Якщо є статичний метод `Symbol.hasInstance`, тоді він просто викликаєтсья: `Class[Symbol.hasInstance](obj)`. Він повинен повернути `true`або`false`, ось і все. Ось як ми можемо задати поведінку`instanceof`.
54
54
55
-
For example:
55
+
Наприклад:
56
56
57
57
```js run
58
-
//setup instanceOf check that assumes that
59
-
//anything with canEat property is an animal
58
+
//задамо перевірку instanceof таким чином,
59
+
//що будь-що із властивістю canEat - це тварина
60
60
classAnimal {
61
61
static [Symbol.hasInstance](obj) {
62
62
if (obj.canEat) returntrue;
@@ -65,24 +65,24 @@ The algorithm of `obj instanceof Class` works roughly as follows:
65
65
66
66
let obj = { canEat:true };
67
67
68
-
alert(obj instanceof Animal); // true: Animal[Symbol.hasInstance](obj) is called
68
+
alert(obj instanceof Animal); // true: Animal[Symbol.hasInstance](obj) було викликано
69
69
```
70
70
71
-
2.Most classes do not have `Symbol.hasInstance`. In that case, the standard logic is used:`obj instanceOf Class`checks whether`Class.prototype`is equal to one of the prototypes in the `obj` prototype chain.
71
+
2.Більшість класів не мають `Symbol.hasInstance`. У цьому випадку використовується стандартна логіка:`obj instanceOf Class`перевіряє чи`Class.prototype`дорівнює одному з прототипів у ланцюжку прототипів `obj`.
72
72
73
-
In other words, compare one after another:
73
+
Іншими словами, прототипи порівнюються один за одним:
Here's the illustration of what `rabbit instanceof Animal` compares with `Animal.prototype`:
102
+
Ось ілюстрація того, як операція`rabbit instanceof Animal`шукає `Animal.prototype` у прототипах:
103
103
104
104

105
105
106
-
By the way, there's also a method [objA.isPrototypeOf(objB)](mdn:js/object/isPrototypeOf), that returns`true`if`objA`is somewhere in the chain of prototypes for`objB`. So the test of`obj instanceof Class`can be rephrased as`Class.prototype.isPrototypeOf(obj)`.
106
+
До речі, є також метод [objA.isPrototypeOf(objB)](mdn:js/object/isPrototypeOf), який повертає`true`якщо`objA`знаходиться десь у ланцюжку прототипів для `objB`. Отже, перевірку `obj instanceof Class`можна замінити на`Class.prototype.isPrototypeOf(obj)`.
107
107
108
-
It's funny, but the `Class` constructor itself does not participate in the check! Only the chain of prototypes and `Class.prototype` matters.
108
+
Цікаво, але сам класс `Class`не бере участі в перевірці! Має значення лише ланцюжок прототипів і`Class.prototype`.
109
109
110
-
That can lead to interesting consequences when a `prototype` property is changed after the object is created.
110
+
Це може призвести до дивних наслідків, коли властивість`prototype`було змінено після створення об’єкта.
111
111
112
-
Like here:
112
+
Як тут:
113
113
114
114
```js run
115
115
function Rabbit() {}
116
116
let rabbit = new Rabbit();
117
117
118
-
// changed the prototype
118
+
// Змінюємо прототип
119
119
Rabbit.prototype = {};
120
120
121
-
// ...not a rabbit any more!
121
+
// ...це більше не rabbit!
122
122
*!*
123
123
alert( rabbit instanceof Rabbit ); // false
124
124
*/!*
125
125
```
126
126
127
-
## Bonus: Object.prototype.toString for the type
127
+
## Бонус:Object.prototype.toStringдля визначення типу
128
128
129
-
We already know that plain objects are converted to string as `[object Object]`:
129
+
Ми вже знаємо, що прості об’єкти перетворюються на рядки як`[object Object]`:
130
130
131
131
```js run
132
132
let obj = {};
133
133
134
134
alert(obj); // [object Object]
135
-
alert(obj.toString()); // the same
135
+
alert(obj.toString()); // теж саме
136
136
```
137
137
138
-
That's their implementation of`toString`. But there's a hidden feature that makes `toString` actually much more powerful than that. We can use it as an extended `typeof` and an alternative for `instanceof`.
138
+
Це їх реалізація метода`toString`. Але є прихована функція, яка робить метод`toString`набагато потужнішим. Ми можемо використовувати його як розширений `typeof`і альтернативу`instanceof`.
139
139
140
-
Sounds strange? Indeed. Let's demystify.
140
+
Звучить дивно? Дійсно. Давайте розбиратися.
141
141
142
-
By [specification](https://tc39.github.io/ecma262/#sec-object.prototype.tostring), the built-in `toString` can be extracted from the object and executed in the context of any other value. And its result depends on that value.
142
+
У [специфікації](https://tc39.github.io/ecma262/#sec-object.prototype.tostring), вбудований метод `toString` можна витягнути з об’єкта та викликати в контексті будь-якого іншого значення. І результат залежить від типу цього значення.
143
143
144
-
-For a number, it will be`[object Number]`
145
-
-For a boolean, it will be`[object Boolean]`
146
-
-For`null`:`[object Null]`
147
-
-For`undefined`:`[object Undefined]`
148
-
-For arrays:`[object Array]`
149
-
-...etc (customizable).
144
+
-Для числа це буде`[object Number]`
145
+
-Для логічного значення це буде`[object Boolean]`
146
+
-Для`null`:`[object Null]`
147
+
-Для`undefined`:`[object Undefined]`
148
+
-Для масивів:`[object Array]`
149
+
-...тощо.
150
150
151
-
Let's demonstrate:
151
+
Давайте продемонструємо:
152
152
153
153
```js run
154
-
// copy toString method into a variable for convenience
154
+
// скопіюємо метод toString у змінну для зручності
Here we used [call](mdn:js/function/call) as described in the chapter [](info:call-apply-decorators) to execute the function `objectToString` in the context `this=arr`.
163
+
Тут ми використали [call](mdn:js/function/call), як описано в розділі [](info:call-apply-decorators), щоб викликати функцію `objectToString` з контекстом `this=arr`.
164
164
165
-
Internally, the `toString` algorithm examines `this` and returns the corresponding result. More examples:
165
+
Всередені алгоритм `toString` перевіряє `this` і повертає відповідний результат. Більше прикладів:
As you can see, the result is exactly `Symbol.toStringTag` (if exists), wrapped into `[object ...]`.
200
+
Як бачите, результатом є саме `Symbol.toStringTag` (якщо існує), загорнутий у`[object ...]`.
201
201
202
-
At the end we have "typeof on steroids" that not only works for primitive data types, but also for built-in objects and even can be customized.
202
+
Наприкінці ми маємо "typeof на стероїдах", який працює не тільки для примітивних типів даних, але й для вбудованих об’єктів і навіть може бути кастомізований.
203
203
204
-
We can use `{}.toString.call` instead of `instanceof` for built-in objects when we want to get the type as a string rather than just to check.
204
+
Ми можемо використати`{}.toString.call`замість `instanceof`для вбудованих об’єктів, коли ми хочемо отримати тип у вигляді рядка, а не просто для перевірки.
205
205
206
-
## Summary
206
+
## Підсумки
207
207
208
-
Let's summarize the type-checking methods that we know:
208
+
Давайте підсумуємо відомі нам методи перевірки типів:
0 commit comments