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/08-prototypes/01-prototype-inheritance/article.md
+19-19Lines changed: 19 additions & 19 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,22 +1,22 @@
1
-
# Prototypal inheritance
1
+
# Прототипное наследование
2
2
3
-
In programming, we often want to take something and extend it.
3
+
В программировании мы часто хотим взять что-то и расширить.
4
4
5
-
For instance, we have a `user`object with its properties and methods, and want to make `admin`and`guest`as slightly modified variants of it. We'd like to reuse what we have in `user`, not copy/reimplement its methods, just build a new object on top of it.
5
+
Например, у нас есть объект `user`со своими свойствами и методами, и мы хотим создать обьекты `admin`и`guest`как его слегка измененные варианты. Мы хотели бы повторно использовать то, что есть у обьекта `user`, не копировать/переопределять его методы, но просто создать новый объект поверх него.
6
6
7
-
*Prototypal inheritance* is a language feature that helps in that.
7
+
*Прототипное наследование* — это особенность языка, которая помогает в этом.
8
8
9
9
## [[Prototype]]
10
10
11
-
In JavaScript, objects have a special hidden property `[[Prototype]]` (as named in the specification), that is either`null` or references another object. That object is called "a prototype":
11
+
В JavaScript объекты имеют специальное скрытое свойство `[[Prototype]]` (как указано в спецификации), которое либо равно`null`, либо ссылается на другой объект. Этот объект называется "прототип":
12
12
13
13

14
14
15
-
That`[[Prototype]]`has a "magical" meaning. When we want to read a property from `object`, and it's missing, JavaScript automatically takes it from the prototype. In programming, such thing is called "prototypal inheritance". Many cool language features and programming techniques are based on it.
15
+
Этот`[[Prototype]]`имеет "магическое" значение. Когда мы хотим прочитать свойство из `объекта`, а оно отсутствует, JavaScript автоматически берет его из прототипа. В программировании такой механизм называется "прототипным наследованием". Многие интересные возможности языка и техники программирования основываются на нем.
16
16
17
-
The property `[[Prototype]]`is internal and hidden, but there are many ways to set it.
17
+
Свойство `[[Prototype]]`является внутренним и скрытым, но есть много способов задать его самостоятельно.
18
18
19
-
One of them is to use `__proto__`, like this:
19
+
Одним из них является использование `__proto__`, например так:
20
20
21
21
```js run
22
22
let animal = {
@@ -31,17 +31,17 @@ rabbit.__proto__ = animal;
31
31
*/!*
32
32
```
33
33
34
-
```smart header="`__proto__`is a historical getter/setter for`[[Prototype]]`"
35
-
Please note that`__proto__`is *not the same* as`[[Prototype]]`. That's a getter/setter for it.
Обратите внимание, что`__proto__`— *не то же самое*, что`[[Prototype]]`. Это геттер/сеттер для него.
36
36
37
-
It exists for historical reasons, in modern language it is replaced with functions `Object.getPrototypeOf/Object.setPrototypeOf` that also get/set the prototype. We'll study the reasons for that and these functions later.
37
+
Он существует по историческим причинам, в современном языке его заменяют функции `Object.getPrototypeOf / Object.setPrototypeOf`, которые также получают/устанавливают прототип. Мы рассмотрим причины этого и эти функции позже.
38
38
39
-
By the specification, `__proto__`must only be supported by browsers, but in fact all environments including server-side support it. For now, as `__proto__`notation is a little bit more intuitively obvious, we'll use it in the examples.
39
+
По спецификации `__proto__`должен поддерживаться только браузерами, но на самом деле все среды, включая серверную, поддерживают его. На данный момент, поскольку нотация `__proto__`немного более понятна, мы будем использовать ее в примерах.
40
40
```
41
41
42
-
If we look for a property in `rabbit`, and it's missing, JavaScript automatically takes it from `animal`.
42
+
Если мы ищем свойство в `rabbit`, и оно отсутствует, JavaScript автоматически берет его из `animal`.
43
43
44
-
For instance:
44
+
Например:
45
45
46
46
```js run
47
47
let animal = {
@@ -55,22 +55,22 @@ let rabbit = {
55
55
rabbit.__proto__ = animal; // (*)
56
56
*/!*
57
57
58
-
// we can find both properties in rabbit now:
58
+
// теперь мы можем найти оба свойства в rabbit:
59
59
*!*
60
60
alert( rabbit.eats ); // true (**)
61
61
*/!*
62
62
alert( rabbit.jumps ); // true
63
63
```
64
64
65
-
Here the line `(*)`sets`animal`to be a prototype of`rabbit`.
65
+
Здесь линия `(*)`устанавливает`animal`как прототип для`rabbit`.
66
66
67
-
Then, when`alert`tries to read property `rabbit.eats``(**)`, it's not in`rabbit`, so JavaScript follows the `[[Prototype]]`reference and finds it in `animal` (look from the bottom up):
67
+
Затем, когда`alert`пытается прочитать свойство `rabbit.eats``(**)`, его нет в`rabbit`, поэтому JavaScript следует по ссылке `[[Prototype]]`и находит ее в `animal` (смотрите снизу вверх):
68
68
69
69

70
70
71
-
Here we can say that "`animal`is the prototype of `rabbit`" or "`rabbit`prototypically inherits from`animal`".
71
+
Здесь иы можем сказать, что "`animal`является прототипом `rabbit`" или "`rabbit`прототипно наследуется от`animal`".
72
72
73
-
So if `animal`has a lot of useful properties and methods, then they become automatically available in`rabbit`. Such properties are called "inherited".
73
+
Так что если у `animal`много полезных свойств и методов, то они автоматически становятся доступными у`rabbit`. Такие свойства называются "унаследованными".
74
74
75
75
If we have a method in `animal`, it can be called on `rabbit`:
0 commit comments