Skip to content

F.prototype #194

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 37 commits into from
Aug 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
4c9ecb9
Prototypal inheritance
VolodymyrSSS Jul 29, 2021
a12ac5e
Update 1-js/08-prototypes/01-prototype-inheritance/article.md
tarasyyyk Aug 3, 2021
497d6f6
Prototypal inheritance with tasks
VolodymyrSSS Aug 3, 2021
13a3867
Merge branch 'master' of https://github.com/VolodymyrSSS/uk.javascrip…
VolodymyrSSS Aug 3, 2021
53fd546
Update 1-js/08-prototypes/01-prototype-inheritance/article.md
tarasyyyk Aug 4, 2021
7fb075d
Merge branch 'master' of https://github.com/VolodymyrSSS/uk.javascrip…
VolodymyrSSS Aug 4, 2021
ccd5639
Update 1-js/08-prototypes/01-prototype-inheritance/article.md
tarasyyyk Aug 4, 2021
29337da
Update 1-js/08-prototypes/01-prototype-inheritance/article.md
tarasyyyk Aug 4, 2021
bab3934
Update 1-js/08-prototypes/01-prototype-inheritance/1-property-after-d…
tarasyyyk Aug 4, 2021
a7fadb3
Update 1-js/08-prototypes/01-prototype-inheritance/2-search-algorithm…
tarasyyyk Aug 4, 2021
b66b466
Update 1-js/08-prototypes/01-prototype-inheritance/2-search-algorithm…
tarasyyyk Aug 4, 2021
90a2be2
Update 1-js/08-prototypes/01-prototype-inheritance/2-search-algorithm…
tarasyyyk Aug 4, 2021
35d0900
Update 1-js/08-prototypes/01-prototype-inheritance/2-search-algorithm…
tarasyyyk Aug 4, 2021
64484aa
Update 1-js/08-prototypes/01-prototype-inheritance/2-search-algorithm…
tarasyyyk Aug 4, 2021
8f81cb8
Update 1-js/08-prototypes/01-prototype-inheritance/3-proto-and-this/t…
tarasyyyk Aug 4, 2021
01b2cee
Update 1-js/08-prototypes/01-prototype-inheritance/3-proto-and-this/t…
tarasyyyk Aug 4, 2021
82e2352
Update 1-js/08-prototypes/01-prototype-inheritance/4-hamster-proto/so…
tarasyyyk Aug 4, 2021
2db53f6
Update 1-js/08-prototypes/01-prototype-inheritance/4-hamster-proto/so…
tarasyyyk Aug 4, 2021
ea5e7d9
Update 1-js/08-prototypes/01-prototype-inheritance/4-hamster-proto/so…
tarasyyyk Aug 4, 2021
cb518cd
Update 1-js/08-prototypes/01-prototype-inheritance/4-hamster-proto/so…
tarasyyyk Aug 4, 2021
70396aa
Update 1-js/08-prototypes/01-prototype-inheritance/4-hamster-proto/so…
tarasyyyk Aug 4, 2021
ffbaa25
Update 1-js/08-prototypes/01-prototype-inheritance/4-hamster-proto/so…
tarasyyyk Aug 4, 2021
65a4ccd
Update 1-js/08-prototypes/01-prototype-inheritance/4-hamster-proto/so…
tarasyyyk Aug 4, 2021
fc9db58
Update 1-js/08-prototypes/01-prototype-inheritance/4-hamster-proto/ta…
tarasyyyk Aug 4, 2021
f3d4949
Update 1-js/08-prototypes/01-prototype-inheritance/4-hamster-proto/ta…
tarasyyyk Aug 4, 2021
6b63291
Corrections
tarasyyyk Aug 4, 2021
4141038
Prototypal inheritance with bugsfix
VolodymyrSSS Aug 4, 2021
42bc1c4
Prototypal inheritance wit bugsfix
VolodymyrSSS Aug 4, 2021
94add02
Prototypal inheritance with bugsfix2
VolodymyrSSS Aug 4, 2021
34baa3a
Prototypal inheritance wit finel touch fix
VolodymyrSSS Aug 5, 2021
8f917dc
F.prototype
VolodymyrSSS Aug 24, 2021
b1b09a2
Update 1-js/08-prototypes/01-prototype-inheritance/3-proto-and-this/t…
tarasyyyk Aug 25, 2021
d7640dc
Update 1-js/08-prototypes/02-function-prototype/article.md
tarasyyyk Aug 25, 2021
9b03403
Update 1-js/08-prototypes/02-function-prototype/article.md
tarasyyyk Aug 25, 2021
d6aca7a
Update 1-js/08-prototypes/02-function-prototype/article.md
tarasyyyk Aug 25, 2021
35aa74e
Update 1-js/08-prototypes/02-function-prototype/article.md
tarasyyyk Aug 25, 2021
0f89b9d
Merge branch 'master' into master
tarasyyyk Aug 25, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ importance: 5

Ми маємо об’єкт `rabbit`, котрий успадковує властивості від об’єкта `animal`.

Якщо ми викличемо `rabbit.eat()`, який з об’єктів буде записана властивість `full`: в `animal` чи `rabbit`?
Якщо ми викличемо `rabbit.eat()`, у який з об’єктів буде записана властивість `full`: в `animal` чи `rabbit`?

```js
let animal = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ let hamster = {

eat(food) {
*!*
// визначається до this.stomach замість this.stomach.push
// визначається до `this.stomach` замість `this.stomach.push`
this.stomach = [food];
*/!*
}
Expand All @@ -39,7 +39,7 @@ speedy.eat("apple");
alert( speedy.stomach ); // apple

// Шлунок хом’ячка 'Lazy' пустий
alert( lazy.stomach ); // <nothing>
alert( lazy.stomach ); // <нічого>
```

Тепер все працює добре, тому що `this.stomach=` не виконує пошук властивості `stomach`. Значення записується прямо в `this` об’єкта.
Expand Down Expand Up @@ -69,12 +69,12 @@ let lazy = {
*/!*
};

// Хом’ячок 'Speedy' знайшов їду
speedy.eat("apple");
alert( speedy.stomach ); // apple
// Хом’ячок `Speedy` знайшов їжу
speedy.eat("яблуко");
alert( speedy.stomach ); // яблуко

// Шлунок хом’ячка 'Lazy' пустий
alert( lazy.stomach ); // <nothing>
// Шлунок хом’ячка `Lazy` пустий
alert( lazy.stomach ); // <нічого>
```

Отже, спільним рішенням може бути те, що всі властивості, які описують стан конкретного об’єкта (подібно як `stomach`), повинні бути записані (визначені) в цьому ж самому об’єкті. Це уникне подібної проблеми.
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@

Answers:
Відповідь:

1. `true`.

The assignment to `Rabbit.prototype` sets up `[[Prototype]]` for new objects, but it does not affect the existing ones.
Визначення `Rabbit.prototype` встановлює властивість `[[Prototype]]` для новоствореного об’єкта, але це жодним чином не впливає на вже існуючий об’єкт.

2. `false`.

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`.
Об’єкти призначаються шляхом посилання на них. Об’єкт з властивістю `Rabbit.prototype` не дублюється, це є той самий об’єкт на який посилаються як через `Rabbit.prototype` так і через властивість `[[Prototype]]` об’єкта `rabbit`.

So when we change its content through one reference, it is visible through the other one.
А отже, коли ми змінюємо контент такого об’єкта через посилання, такі зміни стають видимі і через інші посилання.

3. `true`.

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.
Усі `delete` операції застосовуються безпосередньо на самому об'єкті. Тут `delete rabbit.eats` намагається видалити властивість `eats` з об’єкта `rabbit`, але такої властивості немає. А тому така операція не має ніякого ефекту.

4. `undefined`.

The property `eats` is deleted from the prototype, it doesn't exist any more.
Властивість `eats` видалена з прототипу, вона більше не існує.
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ importance: 5

---

# Changing "prototype"
# Заміна властивості "prototype"

In the code below we create `new Rabbit`, and then try to modify its prototype.
В коді, що показаний нижче, ми створюємо об’єкт `new Rabbit` і потім міняємо його прототип.

In the start, we have this code:
На початку, маємо цей код:

```js run
function Rabbit() {}
Expand All @@ -20,7 +20,7 @@ alert( rabbit.eats ); // true
```


1. We added one more string (emphasized). What will `alert` show now?
1. Ми додали ще рядок коду (виділений). Що покаже тепер `alert`?

```js
function Rabbit() {}
Expand All @@ -37,7 +37,7 @@ alert( rabbit.eats ); // true
alert( rabbit.eats ); // ?
```

2. ...And if the code is like this (replaced one line)?
2. ...А якщо маємо такий код (з видаленим рядком коду)?

```js
function Rabbit() {}
Expand All @@ -54,7 +54,7 @@ alert( rabbit.eats ); // true
alert( rabbit.eats ); // ?
```

3. And like this (replaced one line)?
3. А якщо так (також з видаленим рядком коду)?

```js
function Rabbit() {}
Expand All @@ -71,7 +71,7 @@ alert( rabbit.eats ); // true
alert( rabbit.eats ); // ?
```

4. The last variant:
4. І останній варіант:

```js
function Rabbit() {}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
We can use such approach if we are sure that `"constructor"` property has the correct value.
Так, ми можемо використовувати такий підхід якщо ми впевнені, що властивість `"constructor"` має правильне значення.

For instance, if we don't touch the default `"prototype"`, then this code works for sure:
Для прикладу, якщо ми не чіпаємо властивість за замовчуванням `"prototype"`, тоді цей код буде працювати правильно:

```js run
function User(name) {
Expand All @@ -10,14 +10,14 @@ function User(name) {
let user = new User('John');
let user2 = new user.constructor('Pete');

alert( user2.name ); // Pete (worked!)
alert( user2.name ); // Pete (працює!)
```

It worked, because `User.prototype.constructor == User`.
Код працює, тому що `User.prototype.constructor == User`.

..But if someone, so to speak, overwrites `User.prototype` and forgets to recreate `constructor` to reference `User`, then it would fail.
..Але якщо хтось, якщо можна так виразитись, перезапише `User.prototype` і забуде додати властивість `constructor` в посиланні властивості об’єкта `User`, тоді цей код не буде працювати правильно.

For instance:
Наприклад:

```js run
function User(name) {
Expand All @@ -33,17 +33,17 @@ let user2 = new user.constructor('Pete');
alert( user2.name ); // undefined
```

Why `user2.name` is `undefined`?
Чому `user2.name` є `undefined`?

Here's how `new user.constructor('Pete')` works:
Ось тут пояснення як `new user.constructor('Pete')` працює:

1. First, it looks for `constructor` in `user`. Nothing.
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!).
3. Going further up the chain, `User.prototype` is a plain object, its prototype is the built-in `Object.prototype`.
4. Finally, for the built-in `Object.prototype`, there's a built-in `Object.prototype.constructor == Object`. So it is used.
1. Спочатку, здійснюється пошук у властивості `constructor` об’єкта `user`. Нічого не знаходять.
2. Потім переключаються на ланцюжок прототипу. Прототипом для об’єкта `user` є `User.prototype`, і він також не має властивості `constructor` (тому що ми "забули" визначити його правильним чином!).
3. Йдучи далі по ланцюжку прототипу, визначаємо, що `User.prototype` є простий об’єкт, його прототипом є вбудований глобальний `Object.prototype`.
4. Врешті, для вбудованого `Object.prototype`, є вбудований конструктор глобального об’єкта `Object.prototype.constructor == Object` от він і використовується.

Finally, at the end, we have `let user2 = new Object('Pete')`.
Таким чином, в кінці, ми отримуємо `let user2 = new Object('Pete')`.

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`.
Ймовірно, це не те, що нам потрібно. Ми би хотіли стоврити `new User`, а не `new Object`. Це і є наслідки пропуску властивості `constructor`.

(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).
(на випадок, якщо вас зацікавить, виклик `new Object(...)` перетворює його аргументи на об’єкт. Це в теорії, але на практиці ніхто не викликає `new Object` з аргументами; і загалом, не використовується узагалі `new Object` для створення нових об’єктів).
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ importance: 5

---

# Create an object with the same constructor
# Створення нового об’єкта з одинаковим конструктором

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.
Уявіть собі, у нас є довільний об’єкт `obj`, який створений функцією-конструктором -- ми не знаємо яким саме конструктором, але потрібно створити новий об’єкт використовуючи той самий конструктор.

Can we do it like that?
Чи можна створити новий об’єкт ось так?

```js
let obj2 = new obj.constructor();
```

Give an example of a constructor function for `obj` which lets such code work right. And an example that makes it work wrong.
Покажіть приклад функції-конструктора для обєкта `obj`, який забезпечить правильну роботу такого коду, а також приклад, який, при такому коді, працює неправельно.
Loading