Skip to content

Commit af63d7c

Browse files
committed
2 parents 6b6fb3e + cee65e5 commit af63d7c

2 files changed

Lines changed: 143 additions & 142 deletions

File tree

  • 1-js/06-advanced-functions/12-arrow-functions
  • 9-regular-expressions/03-regexp-character-classes

1-js/06-advanced-functions/12-arrow-functions/article.md

Lines changed: 37 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,26 @@
1-
# Arrow functions revisited
1+
# Снова стрелочные функции
22

3-
Let's revisit arrow functions.
3+
Давайте вернемся к стрелочным функциям.
44

5-
Arrow functions are not just a "shorthand" for writing small stuff.
5+
Стрелочные функции это не просто "сокращение" чтобы меньше писать.
66

7-
JavaScript is full of situations where we need to write a small function, that's executed somewhere else.
7+
При написании JavaScript-кода часто возникают ситуации, когда нам нужно написать небольшую функцию, которая будет выполнена где-то еще.
88

9-
For instance:
9+
Например:
1010

11-
- `arr.forEach(func)` -- `func` is executed by `forEach` for every array item.
12-
- `setTimeout(func)` -- `func` is executed by the built-in scheduler.
13-
- ...there are more.
11+
- `arr.forEach(func)` -- `func` выполняется `forEach` для каждого элемента массива.
12+
- `setTimeout(func)` -- `func` выполняется встроенным планировщиком.
13+
- ...и так далее.
1414

15-
It's in the very spirit of JavaScript to create a function and pass it somewhere.
15+
Это очень в духе JavaScript - создать функцию и передать ее куда-нибудь.
1616

17-
And in such functions we usually don't want to leave the current context.
17+
И в таких функциях мы обычно не хотим выходить из текущего контекста.
1818

19-
## Arrow functions have no "this"
19+
## У стрелочных функций нет "this"
2020

21-
As we remember from the chapter <info:object-methods>, arrow functions do not have `this`. If `this` is accessed, it is taken from the outside.
21+
Как мы помним из главы <info:object-methods>, у стрелочных функций нет `this`. Если происходит обращение к `this`, его значение берется снаружи.
2222

23-
For instance, we can use it to iterate inside an object method:
23+
Например, мы можем использовать это для итерации внутри метода объекта:
2424

2525
```js run
2626
let group = {
@@ -39,9 +39,9 @@ let group = {
3939
group.showList();
4040
```
4141

42-
Here in `forEach`, the arrow function is used, so `this.title` in it is exactly the same as in the outer method `showList`. That is: `group.title`.
42+
Здесь внутри `forEach` использована стрелочная функции, таким образом `this.title` в ней будет иметь точно такое же значение, как в методе `showList`: `group.title`.
4343

44-
If we used a "regular" function, there would be an error:
44+
Если бы мы использовали "обычную" функцию, была бы ошибка:
4545

4646
```js run
4747
let group = {
@@ -61,28 +61,29 @@ let group = {
6161
group.showList();
6262
```
6363

64-
The error occurs because `forEach` runs functions with `this=undefined` by default, so the attempt to access `undefined.title` is made.
64+
Ошибка возникает потому, что `forEach` по умолчанию выполняет функции с `this`, равным `undefined`, и поэтому мы пытаемся обратиться к `undefined.title`.
6565

66-
That doesn't affect arrow functions, because they just don't have `this`.
6766

68-
```warn header="Arrow functions can't run with `new`"
69-
Not having `this` naturally means another limitation: arrow functions can't be used as constructors. They can't be called with `new`.
67+
Это не влияет на стрелочные функции, потому что у них просто нет `this`.
68+
69+
```warn header="Стрелочные функции нельзя использовать с `new`"
70+
Отсутствие `this` естественно ведет к другому ограничению: стрелочные функции не могут быть использованы как конструкторы. Они не могут быть вызваны с `new`.
7071
```
7172
72-
```smart header="Arrow functions VS bind"
73-
There's a subtle difference between an arrow function `=>` and a regular function called with `.bind(this)`:
73+
```smart header="Стрелочные функции VS bind"
74+
Существует тонкая разница между стрелочной функцией `=>` and обычной функцией вызванной с `.bind(this)`:
7475
75-
- `.bind(this)` creates a "bound version" of the function.
76-
- The arrow `=>` doesn't create any binding. The function simply doesn't have `this`. The lookup of `this` is made exactly the same way as a regular variable search: in the outer lexical environment.
76+
- `.bind(this)` создает "связанную версию" функции.
77+
- Стрелка `=>` ничего не привязывает. У функции просто нет `this`. При получении значения `this` - оно, как обычная переменная, берется из внешнего лексического окружения.
7778
```
7879

79-
## Arrows have no "arguments"
80+
## Стрелочные функции не имеют "arguments"
8081

81-
Arrow functions also have no `arguments` variable.
82+
У стрелочных функции также нет переменной `arguments`.
8283

83-
That's great for decorators, when we need to forward a call with the current `this` and `arguments`.
84+
Это отлично подходит для декораторов, когда нам нужно пробросить вызов с текущими `this` и `arguments`.
8485

85-
For instance, `defer(f, ms)` gets a function and returns a wrapper around it that delays the call by `ms` milliseconds:
86+
Например, `defer(f, ms)` принимает функцию и возвращает обертку над ней, которая откладывает вызов на `ms` миллисекунд:
8687

8788
```js run
8889
function defer(f, ms) {
@@ -99,7 +100,7 @@ let sayHiDeferred = defer(sayHi, 2000);
99100
sayHiDeferred("John"); // Hello, John after 2 seconds
100101
```
101102

102-
The same without an arrow function would look like:
103+
То же самое без стрелочной функции выглядело бы:
103104

104105
```js
105106
function defer(f, ms) {
@@ -112,15 +113,15 @@ function defer(f, ms) {
112113
}
113114
```
114115

115-
Here we had to create additional variables `args` and `ctx` so that the function inside `setTimeout` could take them.
116+
Здесь мы были вынуждены создать дополнительные переменные `args` и `ctx`, чтобы функция внутри `setTimeout` могла получить их.
116117

117-
## Summary
118+
## Итого
118119

119-
Arrow functions:
120+
Стрелочные функции:
120121

121-
- Do not have `this`.
122-
- Do not have `arguments`.
123-
- Can't be called with `new`.
124-
- (They also don't have `super`, but we didn't study it. Will be in the chapter <info:class-inheritance>).
122+
- Не имеют `this`.
123+
- Не имеют `arguments`.
124+
- Не могут быть вызваны `new`.
125+
- (У них также нет `super`, но мы про это не говорили. Про это будет в главе <info:class-inheritance>).
125126

126-
That's because they are meant for short pieces of code that do not have their own "context", but rather works in the current one. And they really shine in that use case.
127+
Все это потому что они предназначены для небольшого кода, который не имеет своего "контекста", а работает в текущем. И они отлично справляются с этой задачей.

0 commit comments

Comments
 (0)