Skip to content

Commit eef06a6

Browse files
committed
Translate The instanceof operator part
1 parent 4624611 commit eef06a6

1 file changed

Lines changed: 30 additions & 30 deletions

File tree

1-js/09-classes/06-instanceof/article.md

Lines changed: 30 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,82 +1,82 @@
1-
# Class checking: "instanceof"
1+
# Проверка класса: "instanceof"
22

3-
The `instanceof` operator allows to check whether an object belongs to a certain class. It also takes inheritance into account.
3+
Оператор `instanceof` позволяет проверить, какому классу принадлежит объект, с учетом наследования.
44

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+
Такая проверка может потребоваться во многих случаях. Здесь мы будем использовать ее для создания *полиморфной* функции, которая использует аргументы по-разному в зависимости от их типа.
66

7-
## The instanceof operator [#ref-instanceof]
7+
## Оператор instanceof [#ref-instanceof]
88

9-
The syntax is:
9+
Синтаксис:
1010
```js
1111
obj instanceof Class
1212
```
1313

14-
It returns `true` if `obj` belongs to the `Class` (or a class inheriting from it).
14+
Оператор вернет `true`, если `obj` принадлежит классу `Class` (или класс наследует от него).
1515

16-
For instance:
16+
Например:
1717

1818
```js run
1919
class Rabbit {}
2020
let rabbit = new Rabbit();
2121

22-
// is it an object of Rabbit class?
22+
// это объект класса Rabbit?
2323
*!*
2424
alert( rabbit instanceof Rabbit ); // true
2525
*/!*
2626
```
2727

28-
It also works with constructor functions:
28+
Также это работает с функциями-конструкторами:
2929

3030
```js run
3131
*!*
32-
// instead of class
32+
// вместо класса
3333
function Rabbit() {}
3434
*/!*
3535

3636
alert( new Rabbit() instanceof Rabbit ); // true
3737
```
3838

39-
...And with built-in classes like `Array`:
39+
...И для встроенных классов, таких как `Array`:
4040

4141
```js run
4242
let arr = [1, 2, 3];
4343
alert( arr instanceof Array ); // true
4444
alert( arr instanceof Object ); // true
4545
```
4646

47-
Please note that `arr` also belongs to the `Object` class. That's because `Array` prototypally inherits from `Object`.
47+
Пожалуйста, обратите внимание, что `arr` также принадлежит классу `Object`. Это потому, что `Array` наследуется от `Object`.
4848

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`.
5050

51-
The algorithm of `obj instanceof Class` works roughly as follows:
51+
Алгоритм работы `obj instanceof Class` работает примерно следующим образом:
5252

53-
1. If there's a static method `Symbol.hasInstance`, then use it. Like this:
53+
1. Если имеется статичный метод `Symbol.hasInstance`, тогда используется он. Таким образом:
5454

5555
```js run
56-
// assume anything that canEat is an animal
56+
// предполагаем, все что может есть, - это животное
5757
class Animal {
5858
static [Symbol.hasInstance](obj) {
5959
if (obj.canEat) return true;
6060
}
6161
}
6262

6363
let obj = { canEat: true };
64-
alert(obj instanceof Animal); // true: Animal[Symbol.hasInstance](obj) is called
64+
alert(obj instanceof Animal); // true: вызван Animal[Symbol.hasInstance](obj)
6565
```
6666

67-
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`.
6868

69-
In other words, compare:
69+
Другими словами, сравнивается:
7070
```js
7171
obj.__proto__ === Class.prototype
7272
obj.__proto__.__proto__ === Class.prototype
7373
obj.__proto__.__proto__.__proto__ === Class.prototype
7474
...
7575
```
7676

77-
In the example above `Rabbit.prototype === rabbit.__proto__`, so that gives the answer immediately.
77+
В примере выше `Rabbit.prototype === rabbit.__proto__`, так что результат будет получен немедленно.
7878

79-
In the case of an inheritance, `rabbit` is an instance of the parent class as well:
79+
В случае с наследованием, `rabbit` также является экземпляром своего родительского класса:
8080

8181
```js run
8282
class Animal {}
@@ -87,35 +87,35 @@ The algorithm of `obj instanceof Class` works roughly as follows:
8787
alert(rabbit instanceof Animal); // true
8888
*/!*
8989
// rabbit.__proto__ === Rabbit.prototype
90-
// rabbit.__proto__.__proto__ === Animal.prototype (match!)
90+
// rabbit.__proto__.__proto__ === Animal.prototype (совпадение!)
9191
```
9292

93-
Here's the illustration of what `rabbit instanceof Animal` compares with `Animal.prototype`:
93+
Вот иллюстрация того как `rabbit instanceof Animal` сравнивается с `Animal.prototype`:
9494

9595
![](instanceof.png)
9696

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)`.
9898

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`.
100100

101-
That can lead to interesting consequences when `prototype` is changed.
101+
Это может приводить к интересным последствиям при изменении `prototype`.
102102

103-
Like here:
103+
Как, например, тут:
104104

105105
```js run
106106
function Rabbit() {}
107107
let rabbit = new Rabbit();
108108
109-
// changed the prototype
109+
// заменяем прототип
110110
Rabbit.prototype = {};
111111
112-
// ...not a rabbit any more!
112+
// ...больше не rabbit!
113113
*!*
114114
alert( rabbit instanceof Rabbit ); // false
115115
*/!*
116116
```
117117

118-
That's one of the reasons to avoid changing `prototype`. Just to keep safe.
118+
Это одна из причин избегать изменения `prototype`. Просто для безопасности.
119119

120120
## Bonus: Object toString for the type
121121

0 commit comments

Comments
 (0)