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
6
For instance, here `PowerArray` inherits from the native `Array`:
7
+
Например, в этом примере `PowerArray` наследуется от встроенного `Array`:
7
8
8
9
```js run
9
-
//add one more method to it (can do more)
10
+
//добавим один метод (можно более одного)
10
11
classPowerArrayextendsArray {
11
12
isEmpty() {
12
13
returnthis.length===0;
@@ -21,21 +22,21 @@ alert(filteredArr); // 10, 50
21
22
alert(filteredArr.isEmpty()); // false
22
23
```
23
24
24
-
Please note a very interesting thing. Built-in methods like`filter`, `map`and others -- return new objects of exactly the inherited type. They rely on the `constructor` property to do so.
25
+
Обратите внимание на интересную вещь: встроенные методы, такие как`filter`, `map`и другие возвращают новые объекты созданного пользовательского типа. Для этого они используют свойство `constructor`.
25
26
26
-
In the example above,
27
+
В примере выше,
27
28
```js
28
29
arr.constructor=== PowerArray
29
30
```
30
31
31
-
So when `arr.filter()`is called, it internally creates the new array of results exactly as`new PowerArray`.
32
-
That's actually very cool, because we can keep using`PowerArray`methods further on the result.
32
+
Таким образом, при вызове метода `arr.filter()`он внутри создаёт новый массив с результатами так же, как если бы был использован`new PowerArray`.
33
+
Это замечательно, поскольку можно продолжать использовать методы`PowerArray`далее на результатах.
33
34
34
-
Even more, we can customize that behavior.
35
+
Даже более, мы можем изменить поведение.
35
36
36
-
There's a special static getter `Symbol.species`, if exists, it returns the constructor to use in such cases.
37
+
Специальный статичный геттер `Symbol.species`, если существует, возвращает конструктор, который можно использовать в таких случаях.
37
38
38
-
If we'd like built-in methods like `map`, `filter`will return regular arrays, we can return`Array`in`Symbol.species`, like here:
39
+
Если мы решим возвращать обычный массив из встроенных методов, таких как `map`, `filter`и т. д., мы можем вернуть`Array`из`Symbol.species`, как в этом примере:
39
40
40
41
```js run
41
42
classPowerArrayextendsArray {
@@ -44,7 +45,7 @@ class PowerArray extends Array {
44
45
}
45
46
46
47
*!*
47
-
//built-in methods will use this as the constructor
48
+
//встроенные методы будут использовать этот метот как конструктор
48
49
staticget [Symbol.species]() {
49
50
returnArray;
50
51
}
@@ -54,29 +55,29 @@ class PowerArray extends Array {
54
55
let arr =newPowerArray(1, 2, 5, 10, 50);
55
56
alert(arr.isEmpty()); // false
56
57
57
-
// filter creates new array using arr.constructor[Symbol.species] as constructor
58
+
// filter создаст новый массив используя arr.constructor[Symbol.species] как конструктор
58
59
let filteredArr =arr.filter(item=> item >=10);
59
60
60
61
*!*
61
-
// filteredArr is not PowerArray, but Array
62
+
// filteredArr не является PowerArray, это Array
62
63
*/!*
63
64
alert(filteredArr.isEmpty()); // Error: filteredArr.isEmpty is not a function
64
65
```
65
66
66
-
As you can see, now`.filter`returns`Array`. So the extended functionality is not passed any further.
67
+
Как вы видите, теперь`.filter`возвращает`Array`. Расширенный функционал не будет передаваться далее.
67
68
68
-
## No static inheritance in built-ins
69
+
## Отсутствие статичного наследования встроенных классов
69
70
70
-
Built-in objects have their own static methods, for instance `Object.keys`, `Array.isArray`etc.
71
+
У встроенных объектов есть собственные статичные методы, например `Object.keys`, `Array.isArray`и т. д.
71
72
72
-
And we've already been talking about native classes extending each other: `Array.[[Prototype]] = Object`.
73
+
Мы уже говорили ранее о встроенных классах, которые расширяют друг друга: `Array.[[Prototype]] = Object`.
73
74
74
-
But statics are an exception. Built-in classes don't inherit static properties from each other.
75
+
Но статичные методы - исключение. Встроенные классы не наследуют статичные методы друг друга.
75
76
76
-
In other words, the prototype of built-in constructor `Array`does not point to`Object`. This way`Array`and`Date`do not have `Array.keys`or`Date.keys`. And that feels natural.
77
+
Другими словами, прототип встроенного конструктора `Array`не содержит указателя на`Object`. Таким образом,`Array`и`Date`не содержат `Array.keys`или`Date.keys`. И это выглядит естественно.
77
78
78
-
Here's the picture structure for `Date`and`Object`:
79
+
Ниже вы видите структуру `Date`и`Object`:
79
80
80
81

81
82
82
-
Note, there's no link between`Date`and`Object`. Both `Object`and`Date`exist independently. `Date.prototype`inherits from`Object.prototype`, but that's all.
83
+
Заметьте, здесь нет связи между`Date`и`Object`.`Object`и`Date`существуют независимо. `Date.prototype`наследуется от`Object.prototype`, и только.
0 commit comments