Skip to content

Commit 6e80c6c

Browse files
Merge pull request #175 from Terr1bus/master
1/09/05 (js/classes/extend-natives)
2 parents b107eff + e16c753 commit 6e80c6c

1 file changed

Lines changed: 22 additions & 22 deletions

File tree

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

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

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

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

88
```js run
9-
// add one more method to it (can do more)
9+
// добавим один метод (можно более одного)
1010
class PowerArray extends Array {
1111
isEmpty() {
1212
return this.length === 0;
@@ -21,21 +21,21 @@ alert(filteredArr); // 10, 50
2121
alert(filteredArr.isEmpty()); // false
2222
```
2323

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

26-
In the example above,
26+
В примере выше,
2727
```js
2828
arr.constructor === PowerArray
2929
```
3030

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

34-
Even more, we can customize that behavior.
34+
Более того, мы можем настроить это поведение.
3535

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` и других методах для создания новых объектов.
3737

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`, вот так:
3939

4040
```js run
4141
class PowerArray extends Array {
@@ -44,7 +44,7 @@ class PowerArray extends Array {
4444
}
4545

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

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

6060
*!*
61-
// filteredArr is not PowerArray, but Array
61+
// filteredArr не является PowerArray, это Array
6262
*/!*
6363
alert(filteredArr.isEmpty()); // Error: filteredArr.isEmpty is not a function
6464
```
6565

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

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

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

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

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

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

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

8080
![](object-date-inheritance.png)
8181

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

Comments
 (0)