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
It's in the very spirit of JavaScript to create a function and pass it somewhere.
15
+
Это очень в духе JavaScript, создать функцию и передать ее куда-нибудь.
16
16
17
-
And in such functions we usually don't want to leave the current context.
17
+
И в таких функциях мы обычно не хотим выходить из текущего контекста.
18
18
19
-
## Arrow functions have no "this"
19
+
## У стрелочных функций нет "this"
20
20
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» обращаются, он берется снаружи.
22
22
23
-
For instance, we can use it to iterate inside an object method:
23
+
Например, мы можем использовать это для итерации внутри метода объекта:
24
24
25
25
```js run
26
26
let group = {
@@ -39,9 +39,9 @@ let group = {
39
39
group.showList();
40
40
```
41
41
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`.
43
43
44
-
If we used a "regular" function, there would be an error:
44
+
Если бы мы использовали "обычную" функцию, была бы ошибка:
45
45
46
46
```js run
47
47
let group = {
@@ -61,28 +61,29 @@ let group = {
61
61
group.showList();
62
62
```
63
63
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`.
65
65
66
-
That doesn't affect arrow functions, because they just don't have `this`.
67
66
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`.
70
71
```
71
72
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)`:
74
75
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.
- Стрелка `=>` ничего не привязывает. У функции просто нет `this`. Определние `this` происходит абсолютно так же как и обычный поиск перменной: во внешнем лексическом окружении.
77
78
```
78
79
79
-
## Arrows have no "arguments"
80
+
## Стрелочные функции не имеют "arguments"
80
81
81
-
Arrow functions also have no `arguments` variable.
82
+
У стрелочных функции так же нет переменной `arguments`.
82
83
83
-
That's great for decorators, when we need to forward a call with the current `this`and`arguments`.
84
+
Это отлично подходит для декораторов, когда нам нужно пробросить вызов с текущимим `this`и`arguments`.
84
85
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`миллисекунд:
86
87
87
88
```js run
88
89
functiondefer(f, ms) {
@@ -99,7 +100,7 @@ let sayHiDeferred = defer(sayHi, 2000);
99
100
sayHiDeferred("John"); // Hello, John after 2 seconds
100
101
```
101
102
102
-
The same without an arrow function would look like:
103
+
Тоже самое без стрелочной функции выглядело быД
103
104
104
105
```js
105
106
functiondefer(f, ms) {
@@ -112,15 +113,15 @@ function defer(f, ms) {
112
113
}
113
114
```
114
115
115
-
Here we had to create additional variables`args`and`ctx`so that the function inside `setTimeout`could take them.
116
+
Здесь мы были вынуждены создать дополнительные переменные`args`и`ctx`чтобы функция внутри `setTimeout`могла взять их.
116
117
117
-
## Summary
118
+
## Кратко
118
119
119
-
Arrow functions:
120
+
Стрелочные функции:
120
121
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>).
125
126
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