Skip to content

Commit 173eb31

Browse files
Prototypal inheritance (#167)
* Prototypal inheritance * Update 1-js/08-prototypes/01-prototype-inheritance/article.md * Prototypal inheritance with tasks * Update 1-js/08-prototypes/01-prototype-inheritance/article.md * Update 1-js/08-prototypes/01-prototype-inheritance/article.md * Update 1-js/08-prototypes/01-prototype-inheritance/article.md * Update 1-js/08-prototypes/01-prototype-inheritance/1-property-after-delete/solution.md * Update 1-js/08-prototypes/01-prototype-inheritance/2-search-algorithm/solution.md * Update 1-js/08-prototypes/01-prototype-inheritance/2-search-algorithm/solution.md * Update 1-js/08-prototypes/01-prototype-inheritance/2-search-algorithm/solution.md * Update 1-js/08-prototypes/01-prototype-inheritance/2-search-algorithm/task.md * Update 1-js/08-prototypes/01-prototype-inheritance/2-search-algorithm/task.md * Update 1-js/08-prototypes/01-prototype-inheritance/3-proto-and-this/task.md * Update 1-js/08-prototypes/01-prototype-inheritance/3-proto-and-this/task.md * Update 1-js/08-prototypes/01-prototype-inheritance/4-hamster-proto/solution.md * Update 1-js/08-prototypes/01-prototype-inheritance/4-hamster-proto/solution.md * Update 1-js/08-prototypes/01-prototype-inheritance/4-hamster-proto/solution.md * Update 1-js/08-prototypes/01-prototype-inheritance/4-hamster-proto/solution.md * Update 1-js/08-prototypes/01-prototype-inheritance/4-hamster-proto/solution.md * Update 1-js/08-prototypes/01-prototype-inheritance/4-hamster-proto/solution.md * Update 1-js/08-prototypes/01-prototype-inheritance/4-hamster-proto/solution.md * Update 1-js/08-prototypes/01-prototype-inheritance/4-hamster-proto/task.md * Update 1-js/08-prototypes/01-prototype-inheritance/4-hamster-proto/task.md * Corrections Co-authored-by: Taras <[email protected]>
1 parent 8015523 commit 173eb31

File tree

9 files changed

+137
-138
lines changed

9 files changed

+137
-138
lines changed
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11

2-
1. `true`, taken from `rabbit`.
3-
2. `null`, taken from `animal`.
4-
3. `undefined`, there's no such property any more.
2+
1. `true`, береться з `rabbit`.
3+
2. `null`, береться з `animal`.
4+
3. `undefined`, більше немає такої властивості.

1-js/08-prototypes/01-prototype-inheritance/1-property-after-delete/task.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
importance: 5
1+
Важливість: 5
22

33
---
44

5-
# Working with prototype
5+
# Робота з прототипами
66

7-
Here's the code that creates a pair of objects, then modifies them.
7+
Ось код, у якому створюють пару об’єктів і потім в ході виконання їх модифікують.
88

9-
Which values are shown in the process?
9+
Які значення будуть показані в результаті виконання коду?
1010

1111
```js
1212
let animal = {
@@ -28,4 +28,4 @@ delete animal.jumps;
2828
alert( rabbit.jumps ); // ? (3)
2929
```
3030

31-
There should be 3 answers.
31+
Повинно бути 3 відповіді.

1-js/08-prototypes/01-prototype-inheritance/2-search-algorithm/solution.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11

2-
1. Let's add `__proto__`:
2+
1. Додаймо властивість `__proto__`:
33

44
```js run
55
let head = {
@@ -27,6 +27,6 @@
2727
alert( table.money ); // undefined
2828
```
2929

30-
2. In modern engines, performance-wise, there's no difference whether we take a property from an object or its prototype. They remember where the property was found and reuse it in the next request.
30+
2. Для сучасних рушіїв немає різниці, звідки ми беремо властивість -- з самого об’єкта, чи його прототипу. Рушії запам’ятовують де розташована властивість і при повторному запиті одразу її використовують.
3131

32-
For instance, for `pockets.glasses` they remember where they found `glasses` (in `head`), and next time will search right there. They are also smart enough to update internal caches if something changes, so that optimization is safe.
32+
Наприклад, для `pockets.glasses` вони запам’ятають, що властивість `glasses` знаходиться в об’єкті `head`, і наступного разу шукатимуть її там. Вони також достатньо розумні для поновлення внутрішньої пам’яті, якщо вона була змінена, а тому подібна оптимізація є достатньо безпечною.

1-js/08-prototypes/01-prototype-inheritance/2-search-algorithm/task.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@ importance: 5
22

33
---
44

5-
# Searching algorithm
5+
# Алгоритм пошуку
66

7-
The task has two parts.
7+
Задача має дві частини.
88

9-
Given the following objects:
9+
Ми маємо ось такі об’єкти:
1010

1111
```js
1212
let head = {
@@ -27,5 +27,5 @@ let pockets = {
2727
};
2828
```
2929

30-
1. Use `__proto__` to assign prototypes in a way that any property lookup will follow the path: `pockets` -> `bed` -> `table` -> `head`. For instance, `pockets.pen` should be `3` (found in `table`), and `bed.glasses` should be `1` (found in `head`).
31-
2. Answer the question: is it faster to get `glasses` as `pockets.glasses` or `head.glasses`? Benchmark if needed.
30+
1. Використайте властивість `__proto__` визначивши прототипи таким чином, щоб отримання властивостей було можливим по ось такому шляху: `pockets` -> `bed` -> `table` -> `head`. Для прикладу, `pockets.pen` повинно отримати значення `3` (було знайдено в `table`), а `bed.glasses` отримує значення `1` (було знайдено в `head`).
31+
2. Дайте відповідь: для отримання властивості `glasses` що буде швидше: визначити її так `pockets.glasses` чи так `head.glasses`? При необхідності зробіть порівняльний тест.
Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
**The answer: `rabbit`.**
1+
**Відповідь: `rabbit`.**
22

3-
That's because `this` is an object before the dot, so `rabbit.eat()` modifies `rabbit`.
3+
Це тому, що ключове слово `this` вказує на об’єкт перед крапкою, отже `rabbit.eat()` буде записано в `rabbit`.
44

5-
Property lookup and execution are two different things.
5+
Пошук метода та його виконання - це дві різні речі.
66

7-
The method `rabbit.eat` is first found in the prototype, then executed with `this=rabbit`.
7+
Метод `rabbit.eat` спочатку шукається в прототипі, а потім виконується з умовою `this=rabbit`.

1-js/08-prototypes/01-prototype-inheritance/3-proto-and-this/task.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@ importance: 5
22

33
---
44

5-
# Where does it write?
5+
# Де буде записано?
66

7-
We have `rabbit` inheriting from `animal`.
7+
Ми маємо об’єкт `rabbit`, котрий успадковує властивості від об’єкта `animal`.
88

9-
If we call `rabbit.eat()`, which object receives the `full` property: `animal` or `rabbit`?
9+
Якщо ми викличемо `rabbit.eat()`, який з об’єктів буде записана властивість `full`: в `animal` чи `rabbit`?
1010

1111
```js
1212
let animal = {

1-js/08-prototypes/01-prototype-inheritance/4-hamster-proto/solution.md

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,26 @@
1-
Let's look carefully at what's going on in the call `speedy.eat("apple")`.
1+
Подивімося уважно, що відбувається у виклику `speedy.eat("apple")`.
22

3-
1. The method `speedy.eat` is found in the prototype (`=hamster`), then executed with `this=speedy` (the object before the dot).
3+
1. Метод `speedy.eat` знаходиться в прототипі (`=hamster`), і виконується з `this=speedy` (об’єкт перед крапкою).
44

5-
2. Then `this.stomach.push()` needs to find `stomach` property and call `push` on it. It looks for `stomach` in `this` (`=speedy`), but nothing found.
5+
2. Потім `this.stomach.push()` повинен знайти властивість `stomach` і викликати `push` на ньому. Він шукає `stomach` в `this` (`=speedy`), але нічого не знаходить.
66

7-
3. Then it follows the prototype chain and finds `stomach` in `hamster`.
7+
3. Далі `stomach` йде по ланцюжку прототипів до `hamster`.
88

9-
4. Then it calls `push` on it, adding the food into *the stomach of the prototype*.
9+
4. Потім він викликає `push` на ньому, додаючи їжу до *шлунку прототипу*.
1010

11-
So all hamsters share a single stomach!
11+
Таким чином, усі хом’ячки мають спільний шлунок!
1212

13-
Both for `lazy.stomach.push(...)` and `speedy.stomach.push()`, the property `stomach` is found in the prototype (as it's not in the object itself), then the new data is pushed into it.
13+
Для обох методів `lazy.stomach.push(...)` і `speedy.stomach.push()`, властивість `stomach` знаходисться в прототипі (бо в самих об’єктах такої властивості немає), яка отримує нові дані.
1414

15-
Please note that such thing doesn't happen in case of a simple assignment `this.stomach=`:
15+
Зауважте, що така річ не відбувається у випадку простого визначення `this.stomach=`:
1616

1717
```js run
1818
let hamster = {
1919
stomach: [],
2020

2121
eat(food) {
2222
*!*
23-
// assign to this.stomach instead of this.stomach.push
23+
// визначається до this.stomach замість this.stomach.push
2424
this.stomach = [food];
2525
*/!*
2626
}
@@ -34,17 +34,17 @@ let lazy = {
3434
__proto__: hamster
3535
};
3636

37-
// Speedy one found the food
37+
// Хом’ячок 'Speedy' знайшов їжу
3838
speedy.eat("apple");
3939
alert( speedy.stomach ); // apple
4040

41-
// Lazy one's stomach is empty
41+
// Шлунок хом’ячка 'Lazy' пустий
4242
alert( lazy.stomach ); // <nothing>
4343
```
4444

45-
Now all works fine, because `this.stomach=` does not perform a lookup of `stomach`. The value is written directly into `this` object.
45+
Тепер все працює добре, тому що `this.stomach=` не виконує пошук властивості `stomach`. Значення записується прямо в `this` об’єкта.
4646

47-
Also we can totally avoid the problem by making sure that each hamster has their own stomach:
47+
Також, ми можемо узагалі уникнути проблеми визначивши шлунок для кожного хом’ячка окремо, ось так:
4848

4949
```js run
5050
let hamster = {
@@ -69,12 +69,12 @@ let lazy = {
6969
*/!*
7070
};
7171

72-
// Speedy one found the food
72+
// Хом’ячок 'Speedy' знайшов їду
7373
speedy.eat("apple");
7474
alert( speedy.stomach ); // apple
7575

76-
// Lazy one's stomach is empty
76+
// Шлунок хом’ячка 'Lazy' пустий
7777
alert( lazy.stomach ); // <nothing>
7878
```
7979

80-
As a common solution, all properties that describe the state of a particular object, like `stomach` above, should be written into that object. That prevents such problems.
80+
Отже, спільним рішенням може бути те, що всі властивості, які описують стан конкретного об’єкта (подібно як `stomach`), повинні бути записані (визначені) в цьому ж самому об’єкті. Це уникне подібної проблеми.

1-js/08-prototypes/01-prototype-inheritance/4-hamster-proto/task.md

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@ importance: 5
22

33
---
44

5-
# Why are both hamsters full?
5+
# Чому обидва хом’ячка наситились?
66

7-
We have two hamsters: `speedy` and `lazy` inheriting from the general `hamster` object.
7+
Ми маємо два хом’ячка (об’єкти): `speedy` та `lazy`, які успадковують властивості від загального об’єкта `hamster`.
88

9-
When we feed one of them, the other one is also full. Why? How can we fix it?
9+
Коли ми годуємо одного з них, інший також стає ситим. Але чому? Як ми можемо це виправити?
1010

1111
```js run
1212
let hamster = {
@@ -25,11 +25,10 @@ let lazy = {
2525
__proto__: hamster
2626
};
2727

28-
// This one found the food
28+
// Цей хом’ячок знайшов їду
2929
speedy.eat("apple");
3030
alert( speedy.stomach ); // apple
3131

32-
// This one also has it, why? fix please.
32+
// Але цей також має їжу, чому? Виправте це.
3333
alert( lazy.stomach ); // apple
3434
```
35-

0 commit comments

Comments
 (0)