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

81
81
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.
82
+
Следует отметить, что здесь нет связи между `Date`и`Object`. Как`Object`, так и `Date`существуют независимо. `Date.prototype`наследуется только от `Object.prototype`.
0 commit comments