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
Copy file name to clipboardExpand all lines: 1-js/09-classes/06-instanceof/article.md
+30-30Lines changed: 30 additions & 30 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,82 +1,82 @@
1
-
# Class checking: "instanceof"
1
+
# Проверка класса: "instanceof"
2
2
3
-
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, here we'll use it 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`prototypally inherits from`Object`.
47
+
Пожалуйста, обратите внимание, что `arr`также принадлежит классу `Object`. Это потому, что `Array`наследуется от`Object`.
48
48
49
-
The`instanceof`operator examines the prototype chain for the check, and is also fine-tunable using 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 use it. Like this:
53
+
1.Если имеется статичный метод `Symbol.hasInstance`, тогда используется он. Таким образом:
54
54
55
55
```js run
56
-
//assume anything that canEat is an animal
56
+
//предполагаем, все что может есть, - это животное
57
57
classAnimal {
58
58
static [Symbol.hasInstance](obj) {
59
59
if (obj.canEat) returntrue;
60
60
}
61
61
}
62
62
63
63
let obj = { canEat:true };
64
-
alert(obj instanceof Animal); // true: Animal[Symbol.hasInstance](obj) is called
2.Most classes do not have `Symbol.hasInstance`. In that case, check if`Class.prototype`equals to one of prototypes in the `obj` prototype chain.
67
+
2.Большая часть классов не имеет метода `Symbol.hasInstance`. В этом случае проверяется равен ли `Class.prototype`одному из прототипов в прототипной цепочке `obj`.
Here's the illustration of what `rabbit instanceof Animal` compares with `Animal.prototype`:
93
+
Вот иллюстрация того как `rabbit instanceof Animal`сравнивается с`Animal.prototype`:
94
94
95
95

96
96
97
-
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)`.
97
+
Кстати, есть метод [objA.isPrototypeOf(objB)], которые возвращает`true`, если объект `objA`есть где-то в прототипной цепочки объекта `objB`. Так что `obj instanceof Class`можно перефразировать как`Class.prototype.isPrototypeOf(obj)`.
98
98
99
-
That's funny, but the `Class` constructor itself does not participate in the check! Only the chain of prototypes and `Class.prototype` matters.
99
+
Забавно, но сам конструктор `Class`не участвует в процессе проверки! Важна только цепочка прототипов `Class.prototype`.
100
100
101
-
That can lead to interesting consequences when `prototype` is changed.
101
+
Это может приводить к интересным последствиям при изменении `prototype`.
102
102
103
-
Like here:
103
+
Как, например, тут:
104
104
105
105
```js run
106
106
function Rabbit() {}
107
107
let rabbit = new Rabbit();
108
108
109
-
// changed the prototype
109
+
// заменяем прототип
110
110
Rabbit.prototype = {};
111
111
112
-
// ...not a rabbit any more!
112
+
// ...больше не rabbit!
113
113
*!*
114
114
alert( rabbit instanceof Rabbit ); // false
115
115
*/!*
116
116
```
117
117
118
-
That's one of the reasons to avoid changing `prototype`. Just to keep safe.
118
+
Это одна из причин избегать изменения `prototype`. Просто для безопасности.
0 commit comments