Skip to content

Commit e34051b

Browse files
committed
Translate the topic about new Function syntax
1 parent 1c7a55e commit e34051b

1 file changed

Lines changed: 49 additions & 48 deletions

File tree

  • 1-js/06-advanced-functions/07-new-function
Lines changed: 49 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,137 +1,138 @@
11

2-
# The "new Function" syntax
2+
# Синтаксис "new Function"
33

4-
There's one more way to create a function. It's rarely used, but sometimes there's no alternative.
4+
Существует ещё один вариант объявлять функции. Он используется крайне редко, но иногда другого решения не найти.
55

6-
## Syntax
6+
## Синтаксис
77

8-
The syntax for creating a function:
8+
Синтаксис для объявления функции:
99

1010
```js
1111
let func = new Function ([arg1[, arg2[, ...argN]],] functionBody)
1212
```
1313

14-
In other words, function parameters (or, more precisely, names for them) go first, and the body is last. All arguments are strings.
14+
Другими словами, параметры функции (или, более точно, их имена) идут первыми аргументами, тело функци - последним. Обратите внимание на то, что всё аргументы это строки.
1515

16-
It's easier to understand by looking at an example. Here's a function with two arguments:
16+
Это проще понять на следующем примере. Здесь объявлена функция с двумя аргументами:
1717

1818
```js run
19-
let sum = new Function('a', 'b', 'return a + b');
19+
let sum = new Function('a', 'b', 'return a + b');
2020

2121
alert( sum(1, 2) ); // 3
2222
```
2323

24-
If there are no arguments, then there's only a single argument, the function body:
24+
Если у функции нет аргументов, тогда необходимо объявить только один аргумент - тело функции:
2525

2626
```js run
2727
let sayHi = new Function('alert("Hello")');
2828

2929
sayHi(); // Hello
3030
```
3131

32-
The major difference from other ways we've seen is that the function is created literally from a string, that is passed at run time.
32+
Главное отличие от других способов объявления функции, которые были рассмотрены ранее, заключается в том, что функция создаётся полностью «на лету» из строки.
3333

34-
All previous declarations required us, programmers, to write the function code in the script.
34+
Всё предыдущие объявления требовали от нас, программистов, писать объявление функции в скрипте.
3535

36-
But `new Function` allows to turn any string into a function. For example, we can receive a new function from a server and then execute it:
36+
Но `new Function` позволяет превратить любую строку в функцию. Например, мы можем получить новую функцию с сервера и затем выполнить ее:
3737

3838
```js
39-
let str = ... receive the code from a server dynamically ...
39+
let str = ... код, полученный с сервера динамически ...
4040

4141
let func = new Function(str);
4242
func();
4343
```
4444

45-
It is used in very specific cases, like when we receive code from a server, or to dynamically compile a function from a template. The need for that usually arises at advanced stages of development.
45+
Это используется в очень специфических случаях, например, когда мы получаем код с сервера для динамической компиляции функции. Необходимость в этом возникает на продвинутых этапах разработки.
4646

47-
## Closure
47+
## Замыкание
4848

49-
Usually, a function remembers where it was born in the special property `[[Environment]]`. It references the Lexical Environment from where it's created.
49+
Обычно функция помнит, где родилась, в специальном свойстве `[[Environment]]`. Это ссылка на Лексическое окружение (Lexical Environment), в котором она создана.
5050

51-
But when a function is created using `new Function`, its `[[Environment]]` references not the current Lexical Environment, but instead the global one.
51+
Но когда функция создаётся используя `new Function`, её `[[Environment]]` - это ссылка не на текущее Лексическое окружение, а на глобальное.
5252

5353
```js run
5454

5555
function getFunc() {
56-
let value = "test";
56+
let value = "test";
5757

5858
*!*
59-
let func = new Function('alert(value)');
59+
let func = new Function('alert(value)');
6060
*/!*
6161

62-
return func;
62+
return func;
6363
}
6464

65-
getFunc()(); // error: value is not defined
65+
getFunc()(); // ошибка: значение не определено
6666
```
6767

68-
Compare it with the regular behavior:
68+
Сравним это с обычным объявлением:
6969

70-
```js run
70+
```js run
7171
function getFunc() {
72-
let value = "test";
72+
let value = "test";
7373

7474
*!*
75-
let func = function() { alert(value); };
75+
let func = function() { alert(value); };
7676
*/!*
7777

78-
return func;
78+
return func;
7979
}
8080

81-
getFunc()(); // *!*"test"*/!*, from the Lexical Environment of getFunc
81+
getFunc()(); // *!*"test"*/!*, из лексического окружения функции getFunc
8282
```
8383

84-
This special feature of `new Function` looks strange, but appears very useful in practice.
84+
Эта особенность `new Function` выглядит странно, но оказывается очень полезной на практике.
8585

86-
Imagine that we must create a function from a string. The code of that function is not known at the time of writing the script (that's why we don't use regular functions), but will be known in the process of execution. We may receive it from the server or from another source.
86+
Представь, что мы должны создать функцию из строки. Код этой функции не известен во время написания скрипта (поэтому не используем обычно объявление функций), но будет известно только в процессе выпаолнения. Мы можем полчить её с сервера или другого ресурса.
8787

88-
Our new function needs to interact with the main script.
88+
Наша новая функция должна взаимодействовать с основным скриптом.
8989

90-
Perhaps we want it to be able to access outer local variables?
90+
А что, если мы хотим, чтобы она имела доступ к внешним локальным переменным родителя?
9191

92-
The problem is that before JavaScript is published to production, it's compressed using a *minifier* -- a special program that shrinks code by removing extra comments, spaces and -- what's important, renames local variables into shorter ones.
92+
Проблема в том, что до развёртывания/публикации JavaScript кода на продакшене, код сжимается с помощью *минификатора (minifier)* - специальная программа, которая сокращает код, удаляя комментарии, лишние пробелы, и, что самое главное, переименовывает локальные переменные в более короткие.
9393

94-
For instance, if a function has `let userName`, minifier replaces it `let a` (or another letter if this one is occupied), and does it everywhere. That's usually a safe thing to do, because the variable is local, nothing outside the function can access it. And inside the function, minifier replaces every mention of it. Minifiers are smart, they analyze the code structure, so they don't break anything. They're not just a dumb find-and-replace.
94+
Например, если в функция объявляется переменная `let userName`, то минификатор изменяет её на `let a` (или другую букву, если она не занята), и изменяет её везде. Обычно так делать безопасно, потому что переменная является локальной и никто снаружи не имеет к ней достп. И внутри функции минификатор заменяет каждое её упоминание. Минификаторы достаточно умные. Они не просто "тупой" поиск-замена, они анализируют структуру кода, и поэтому ничего не ломают.
9595

96-
But, if `new Function` could access outer variables, then it would be unable to find `userName`, since this is passed in as a string *after* the code is minified.
96+
Но, если `new Function` может получить доступ к внешним локальным переменным родителя, то она не сможет найти `userName`, так как она выполняется *после* минификации кода.
9797

98-
**Even if we could access outer lexical environment in `new Function`, we would have problems with minifiers.**
98+
**Даже если бы мы могли получить доступ к внешнему лексическому окружению `new Function`, у нас были бы проблемы с миниификаторами.**
9999

100-
The "special feature" of `new Function` saves us from mistakes.
100+
"Особое свойство" `new Function` бережёт нас от ошибок.
101101

102-
And it enforces better code. If we need to pass something to a function created by `new Function`, we should pass it explicitly as an argument.
102+
Это обеспечивает лучший код. Если нам необходимо что-то передать функции, объявленной через `new Function`, мы должны передать это явно, как аргумент.
103103

104-
Our "sum" function actually does that right:
104+
Наша "sum" функция, на самом деле, делает это правильно:
105105

106-
```js run
106+
```js run
107107
*!*
108108
let sum = new Function('a', 'b', 'return a + b');
109109
*/!*
110110

111111
let a = 1, b = 2;
112112

113113
*!*
114-
// outer values are passed as arguments
114+
// Внешние значения переданы как аргументы
115115
alert( sum(a, b) ); // 3
116116
*/!*
117117
```
118118

119-
## Summary
119+
## Итого
120120

121-
The syntax:
121+
Синтаксис:
122122

123123
```js
124124
let func = new Function(arg1, arg2, ..., body);
125125
```
126126

127-
For historical reasons, arguments can also be given as a comma-separated list.
127+
Аршументы, по историческим причинам, также могут быть объявлены через запятую в одной строке.
128128

129-
These three mean the same:
129+
Эти 3 примера ниже эквивалентны:
130130

131-
```js
132-
new Function('a', 'b', 'return a + b'); // basic syntax
133-
new Function('a,b', 'return a + b'); // comma-separated
134-
new Function('a , b', 'return a + b'); // comma-separated with spaces
131+
```js
132+
new Function('a', 'b', 'return a + b'); // стандартный синтаксис
133+
new Function('a,b', 'return a + b'); // через запятую в одной строке
134+
new Function('a , b', 'return a + b'); // через запятую с пробелами в одной строке
135135
```
136136

137-
Functions created with `new Function`, have `[[Environment]]` referencing the global Lexical Environment, not the outer one. Hence, they cannot use outer variables. But that's actually good, because it saves us from errors. Passing parameters explicitly is a much better method architecturally and causes no problems with minifiers.
137+
Функции, объявленные через `new Function`, имеют `[[Environment]]` ссылающийся на глобыльное Лексическое окружение, не на родительское. Следовательно, они не могут использовать внешние локальные переменные родителя. Но это, на самом деле, хорошо, потому что это избавляет нас от ошибок. Переданные параметры явно являются лучшим архитектурным решением и это не вызывает проблем у минификаторов.
138+

0 commit comments

Comments
 (0)