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
Built-in classes like Array, Map and others are extendable also.
4
+
Вбудовані класи, такі як Array, Map та інші, також розширюються.
5
5
6
-
For instance, here `PowerArray`inherits from the native`Array`:
6
+
Наприклад, ось тут `PowerArray`успадковується від вбудованого`Array`:
7
7
8
8
```js run
9
-
//add one more method to it (can do more)
9
+
//додамо до нього ще один метод (можна більше)
10
10
classPowerArrayextendsArray {
11
11
isEmpty() {
12
12
returnthis.length===0;
@@ -21,20 +21,20 @@ alert(filteredArr); // 10, 50
21
21
alert(filteredArr.isEmpty()); // false
22
22
```
23
23
24
-
Please note a very interesting thing. Built-in methods like `filter`, `map`and others -- return new objects of exactly the inherited type `PowerArray`. Their internal implementation uses the object's `constructor` property for that.
24
+
Зверніть увагу на дуже цікаву річ. Вбудовані методи, такі як `filter`, `map`та інші, повертають нові об’єкти точно успадкованого типу `PowerArray`. Їхня внутрішня реалізація використовує для цього властивість об’єкта `constructor`.
25
25
26
-
In the example above,
26
+
У вищенаведеному прикладі,
27
27
```js
28
28
arr.constructor=== PowerArray
29
29
```
30
30
31
-
When `arr.filter()` is called, it internally creates the new array of results using exactly `arr.constructor`, not basic `Array`. That's actually very cool, because we can keep using `PowerArray`methods further on the result.
31
+
Коли викликається `arr.filter()`, він внутрішньо створює новий масив результатів, використовуючи саме `arr.constructor`, а не базовий `Array`. Насправді це дуже круто, тому що ми можемо продовжувати використовувати методи `PowerArray`і далі для отримання результату.
32
32
33
-
Even more, we can customize that behavior.
33
+
Щобільше, ми можемо налаштувати таку поведінку.
34
34
35
-
We can add a special static getter `Symbol.species` to the class. If it exists, it should return the constructor that JavaScript will use internally to create new entities in`map`, `filter`and so on.
35
+
Ми можемо додати до класу спеціальний статичний геттер `Symbol.species`. Якщо він існує, то повинен повернути конструктор, який JavaScript буде використовувати внутрішньо для створення нових об’єктів у`map`, `filter`тощо.
36
36
37
-
If we'd like built-in methods like `map`or`filter` to return regular arrays, we can return`Array`in`Symbol.species`, like here:
37
+
Якщо ж ми хочемо, щоб вбудовані методи, такі як `map`або`filter`, повертали звичайні масиви, ми можемо повернути`Array`у`Symbol.species`, як тут:
38
38
39
39
```js run
40
40
classPowerArrayextendsArray {
@@ -43,7 +43,7 @@ class PowerArray extends Array {
43
43
}
44
44
45
45
*!*
46
-
//built-in methods will use this as the constructor
46
+
//вбудовані методи використовуватимуть це як конструктор
47
47
staticget [Symbol.species]() {
48
48
returnArray;
49
49
}
@@ -53,37 +53,37 @@ class PowerArray extends Array {
53
53
let arr =newPowerArray(1, 2, 5, 10, 50);
54
54
alert(arr.isEmpty()); // false
55
55
56
-
// filter creates new array using arr.constructor[Symbol.species] as constructor
56
+
// filter створює новий масив, використовуючи arr.constructor[Symbol.species] як конструктор
57
57
let filteredArr =arr.filter(item=> item >=10);
58
58
59
59
*!*
60
-
// filteredArr is not PowerArray, but Array
60
+
// filteredArr - це не PowerArray, а Array
61
61
*/!*
62
62
alert(filteredArr.isEmpty()); // Error: filteredArr.isEmpty is not a function
63
63
```
64
64
65
-
As you can see, now`.filter`returns`Array`. So the extended functionality is not passed any further.
65
+
Як бачите, тепер`.filter`повертає`Array`. Таким чином, розширена функціональність не передається далі.
66
66
67
-
```smart header="Other collections work similarly"
68
-
Other collections, such as `Map` and `Set`, work alike. They also use `Symbol.species`.
67
+
```smart header="Інші колекції працюють аналогічно"
68
+
Інші колекції, такі як `Map` і `Set`, працюють аналогічно. Вони також використовують `Symbol.species`.
69
69
```
70
70
71
-
## No static inheritance in built-ins
71
+
## Відсутність статичного спадкування вбудованих класів
72
72
73
-
Built-in objects have their own static methods, for instance `Object.keys`, `Array.isArray`etc.
73
+
Вбудовані об’єкти мають власні статичні методи, наприклад `Object.keys`, `Array.isArray`тощо.
74
74
75
-
As we already know, native classes extend each other. For instance, `Array`extends`Object`.
75
+
Як ми вже знаємо, вбудовані класи розширюють один одного. Наприклад, `Array`розширює`Object`.
76
76
77
-
Normally, when one class extends another, both static and non-static methods are inherited. That was thoroughly explained in the article [](info:static-properties-methods#statics-and-inheritance).
77
+
Зазвичай, коли один клас розширює інший, успадковуються як статичні, так і нестатичні методи. Це детально описано в статті [](info:static-properties-methods#static-and-inheritance).
78
78
79
-
But built-in classes are an exception. They don't inherit statics from each other.
79
+
Але вбудовані класи є винятком. Вони не успадковують статику один від одного.
80
80
81
-
For example, both`Array` and`Date`inherit from`Object`, so their instances have methods from`Object.prototype`. But`Array.[[Prototype]]`does not reference`Object`, so there's no, for instance, `Array.keys()` (or`Date.keys()`) static method.
81
+
Наприклад, і`Array`, і`Date`успадковуються від`Object`, тому їхні екземпляри мають методи з`Object.prototype`. Але`Array.[[Prototype]]`не посилається на`Object`, тому не існує, наприклад, `Array.keys()` (або`Date.keys()`) статичного методу.
82
82
83
-
Here's the picture structure for `Date`and`Object`:
83
+
Ось структура зображення для `Date`та`Object`:
84
84
85
85

86
86
87
-
As you can see, there's no link between `Date`and`Object`. They are independent, only`Date.prototype`inherits from`Object.prototype`.
87
+
Як бачите, немає зв’язку між `Date`і`Object`. Вони незалежні, лише`Date.prototype`успадковується від`Object.prototype`.
88
88
89
-
That's an important difference of inheritance between built-in objects compared to what we get with`extends`.
89
+
Це важлива відмінність успадкування між вбудованими об’єктами в порівнянні з тим, що ми отримуємо за допомогою`extends`.
0 commit comments