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
{{ message }}
Repository navigation
Commit f9c04f3
Browse filesBrowse the repository at this point in the historyBrowse files
Copy file name to clipboardExpand all lines: 1-js/08-prototypes/01-prototype-inheritance/4-hamster-proto/solution.md
+7-7Lines changed: 7 additions & 7 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -20,7 +20,7 @@ let hamster = {
20
20
21
21
eat(food) {
22
22
*!*
23
-
// визначається до this.stomach замість this.stomach.push
23
+
// визначається до `this.stomach` замість `this.stomach.push`
24
24
this.stomach= [food];
25
25
*/!*
26
26
}
@@ -39,7 +39,7 @@ speedy.eat("apple");
39
39
alert( speedy.stomach ); // apple
40
40
41
41
// Шлунок хом’ячка 'Lazy' пустий
42
-
alert( lazy.stomach ); // <nothing>
42
+
alert( lazy.stomach ); // <нічого>
43
43
```
44
44
45
45
Тепер все працює добре, тому що `this.stomach=` не виконує пошук властивості `stomach`. Значення записується прямо в `this` об’єкта.
@@ -69,12 +69,12 @@ let lazy = {
69
69
*/!*
70
70
};
71
71
72
-
// Хом’ячок 'Speedy' знайшов їду
73
-
speedy.eat("apple");
74
-
alert( speedy.stomach ); //apple
72
+
// Хом’ячок `Speedy` знайшов їжу
73
+
speedy.eat("яблуко");
74
+
alert( speedy.stomach ); //яблуко
75
75
76
-
// Шлунок хом’ячка 'Lazy' пустий
77
-
alert( lazy.stomach ); // <nothing>
76
+
// Шлунок хом’ячка `Lazy` пустий
77
+
alert( lazy.stomach ); // <нічого>
78
78
```
79
79
80
80
Отже, спільним рішенням може бути те, що всі властивості, які описують стан конкретного об’єкта (подібно як `stomach`), повинні бути записані (визначені) в цьому ж самому об’єкті. Це уникне подібної проблеми.
The assignment to `Rabbit.prototype`sets up`[[Prototype]]`for new objects, but it does not affect the existing ones.
6
+
Визначення `Rabbit.prototype`встановлює властивість`[[Prototype]]`для новоствореного об’єкта, але це жодним чином не впливає на вже існуючий об’єкт.
7
7
8
8
2.`false`.
9
9
10
-
Objects are assigned by reference. The object from`Rabbit.prototype`is not duplicated, it's still a single object referenced both by `Rabbit.prototype`and by the `[[Prototype]]`of`rabbit`.
10
+
Об’єкти призначаються шляхом посилання на них. Об’єкт з властивістю`Rabbit.prototype`не дублюється, це є той самий об’єкт на який посилаються як через `Rabbit.prototype`так і через властивість `[[Prototype]]`об’єкта`rabbit`.
11
11
12
-
So when we change its content through one reference, it is visible through the other one.
12
+
А отже, коли ми змінюємо контент такого об’єкта через посилання, такі зміни стають видимі і через інші посилання.
13
13
14
14
3.`true`.
15
15
16
-
All`delete`operations are applied directly to the object. Here`delete rabbit.eats`tries to remove`eats`property from`rabbit`, but it doesn't have it. So the operation won't have any effect.
16
+
Усі`delete`операції застосовуються безпосередньо на самому об'єкті. Тут`delete rabbit.eats`намагається видалити властивість`eats`з об’єкта`rabbit`, але такої властивості немає. А тому така операція не має ніякого ефекту.
17
17
18
18
4.`undefined`.
19
19
20
-
The property `eats`is deleted from the prototype, it doesn't exist any more.
20
+
Властивість `eats`видалена з прототипу, вона більше не існує.
We can use such approach if we are sure that `"constructor"`property has the correct value.
1
+
Так, ми можемо використовувати такий підхід якщо ми впевнені, що властивість `"constructor"`має правильне значення.
2
2
3
-
For instance, if we don't touch the default `"prototype"`, then this code works for sure:
3
+
Для прикладу, якщо ми не чіпаємо властивість за замовчуванням `"prototype"`, тоді цей код буде працювати правильно:
4
4
5
5
```js run
6
6
functionUser(name) {
@@ -10,14 +10,14 @@ function User(name) {
10
10
let user =newUser('John');
11
11
let user2 =newuser.constructor('Pete');
12
12
13
-
alert( user2.name ); // Pete (worked!)
13
+
alert( user2.name ); // Pete (працює!)
14
14
```
15
15
16
-
It worked, because`User.prototype.constructor == User`.
16
+
Код працює, тому що`User.prototype.constructor == User`.
17
17
18
-
..But if someone, so to speak, overwrites`User.prototype`and forgets to recreate`constructor`to reference `User`, then it would fail.
18
+
..Але якщо хтось, якщо можна так виразитись, перезапише`User.prototype`і забуде додати властивість`constructor`в посиланні властивості об’єкта `User`, тоді цей код не буде працювати правильно.
19
19
20
-
For instance:
20
+
Наприклад:
21
21
22
22
```js run
23
23
functionUser(name) {
@@ -33,17 +33,17 @@ let user2 = new user.constructor('Pete');
33
33
alert( user2.name ); // undefined
34
34
```
35
35
36
-
Why`user2.name`is`undefined`?
36
+
Чому`user2.name`є`undefined`?
37
37
38
-
Here's how `new user.constructor('Pete')`works:
38
+
Ось тут пояснення як `new user.constructor('Pete')`працює:
39
39
40
-
1.First, it looks for `constructor`in`user`. Nothing.
41
-
2.Then it follows the prototype chain. The prototype of`user`is`User.prototype`, and it also has no `constructor` (because we "forgot" to set it right!).
42
-
3.Going further up the chain, `User.prototype`is a plain object, its prototype is the built-in`Object.prototype`.
43
-
4.Finally, for the built-in `Object.prototype`, there's a built-in `Object.prototype.constructor == Object`. So it is used.
40
+
1.Спочатку, здійснюється пошук у властивості `constructor`об’єкта`user`. Нічого не знаходять.
41
+
2.Потім переключаються на ланцюжок прототипу. Прототипом для об’єкта`user`є`User.prototype`, і він також не має властивості `constructor` (тому що ми "забули" визначити його правильним чином!).
42
+
3.Йдучи далі по ланцюжку прототипу, визначаємо, що `User.prototype`є простий об’єкт, його прототипом є вбудований глобальний`Object.prototype`.
43
+
4.Врешті, для вбудованого `Object.prototype`, є вбудований конструктор глобального об’єкта `Object.prototype.constructor == Object` от він і використовується.
44
44
45
-
Finally, at the end, we have`let user2 = new Object('Pete')`.
45
+
Таким чином, в кінці, ми отримуємо`let user2 = new Object('Pete')`.
46
46
47
-
Probably, that's not what we want. We'd like to create`new User`, not `new Object`. That's the outcome of the missing`constructor`.
47
+
Ймовірно, це не те, що нам потрібно. Ми би хотіли стоврити`new User`, а не `new Object`. Це і є наслідки пропуску властивості`constructor`.
48
48
49
-
(Just in case you're curious, the`new Object(...)`call converts its argument to an object. That's a theoretical thing, in practice no one calls `new Object`with a value, and generally we don't use `new Object`to make objects at all).
49
+
(на випадок, якщо вас зацікавить, виклик`new Object(...)`перетворює його аргументи на об’єкт. Це в теорії, але на практиці ніхто не викликає `new Object`з аргументами; і загалом, не використовується узагалі `new Object`для створення нових об’єктів).
Copy file name to clipboardExpand all lines: 1-js/08-prototypes/02-function-prototype/4-new-object-same-constructor/task.md
+4-4Lines changed: 4 additions & 4 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -2,14 +2,14 @@ importance: 5
2
2
3
3
---
4
4
5
-
# Create an object with the same constructor
5
+
# Створення нового об’єкта з одинаковим конструктором
6
6
7
-
Imagine, we have an arbitrary object`obj`, created by a constructor function -- we don't know which one, but we'd like to create a new object using it.
7
+
Уявіть собі, у нас є довільний об’єкт`obj`, який створений функцією-конструктором -- ми не знаємо яким саме конструктором, але потрібно створити новий об’єкт використовуючи той самий конструктор.
8
8
9
-
Can we do it like that?
9
+
Чи можна створити новий об’єкт ось так?
10
10
11
11
```js
12
12
let obj2 =newobj.constructor();
13
13
```
14
14
15
-
Give an example of a constructor function for `obj` which lets such code work right. And an example that makes it work wrong.
15
+
Покажіть приклад функції-конструктора для обєкта `obj`, який забезпечить правильну роботу такого коду, а також приклад, який, при такому коді, працює неправельно.
0 commit comments