Skip to content

Commit 6b6fb3e

Browse files
committed
translate classes_extend-natives
1 parent bf93ead commit 6b6fb3e

1 file changed

Lines changed: 22 additions & 21 deletions

File tree

Lines changed: 22 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11

2-
# Extending built-in classes
2+
# Расширение встроенных классов
33

4-
Built-in classes like Array, Map and others are extendable also.
4+
Базовые классы, такие как Array, Map и другие могу быть также расширены.
55

66
For instance, here `PowerArray` inherits from the native `Array`:
7+
Например, в этом примере `PowerArray` наследуется от встроенного `Array`:
78

89
```js run
9-
// add one more method to it (can do more)
10+
// добавим один метод (можно более одного)
1011
class PowerArray extends Array {
1112
isEmpty() {
1213
return this.length === 0;
@@ -21,21 +22,21 @@ alert(filteredArr); // 10, 50
2122
alert(filteredArr.isEmpty()); // false
2223
```
2324

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`.
2526

26-
In the example above,
27+
В примере выше,
2728
```js
2829
arr.constructor === PowerArray
2930
```
3031

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` далее на результатах.
3334

34-
Even more, we can customize that behavior.
35+
Даже более, мы можем изменить поведение.
3536

36-
There's a special static getter `Symbol.species`, if exists, it returns the constructor to use in such cases.
37+
Специальный статичный геттер `Symbol.species`, если существует, возвращает конструктор, который можно использовать в таких случаях.
3738

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`, как в этом примере:
3940

4041
```js run
4142
class PowerArray extends Array {
@@ -44,7 +45,7 @@ class PowerArray extends Array {
4445
}
4546

4647
*!*
47-
// built-in methods will use this as the constructor
48+
// встроенные методы будут использовать этот метот как конструктор
4849
static get [Symbol.species]() {
4950
return Array;
5051
}
@@ -54,29 +55,29 @@ class PowerArray extends Array {
5455
let arr = new PowerArray(1, 2, 5, 10, 50);
5556
alert(arr.isEmpty()); // false
5657

57-
// filter creates new array using arr.constructor[Symbol.species] as constructor
58+
// filter создаст новый массив используя arr.constructor[Symbol.species] как конструктор
5859
let filteredArr = arr.filter(item => item >= 10);
5960

6061
*!*
61-
// filteredArr is not PowerArray, but Array
62+
// filteredArr не является PowerArray, это Array
6263
*/!*
6364
alert(filteredArr.isEmpty()); // Error: filteredArr.isEmpty is not a function
6465
```
6566

66-
As you can see, now `.filter` returns `Array`. So the extended functionality is not passed any further.
67+
Как вы видите, теперь `.filter` возвращает `Array`. Расширенный функционал не будет передаваться далее.
6768

68-
## No static inheritance in built-ins
69+
## Отсутствие статичного наследования встроенных классов
6970

70-
Built-in objects have their own static methods, for instance `Object.keys`, `Array.isArray` etc.
71+
У встроенных объектов есть собственные статичные методы, например `Object.keys`, `Array.isArray` и т. д.
7172

72-
And we've already been talking about native classes extending each other: `Array.[[Prototype]] = Object`.
73+
Мы уже говорили ранее о встроенных классах, которые расширяют друг друга: `Array.[[Prototype]] = Object`.
7374

74-
But statics are an exception. Built-in classes don't inherit static properties from each other.
75+
Но статичные методы - исключение. Встроенные классы не наследуют статичные методы друг друга.
7576

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`. И это выглядит естественно.
7778

78-
Here's the picture structure for `Date` and `Object`:
79+
Ниже вы видите структуру `Date` и `Object`:
7980

8081
![](object-date-inheritance.png)
8182

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

Comments
 (0)