Skip to content

Commit 35999e5

Browse files
authored
The "new Function" syntax (#199)
1 parent 41ded27 commit 35999e5

File tree

1 file changed

+41
-41
lines changed
  • 1-js/06-advanced-functions/07-new-function

1 file changed

+41
-41
lines changed
Lines changed: 41 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,60 @@
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-
The function is created with the arguments `arg1...argN` and the given `functionBody`.
14+
Функція створюється з аргументами `arg1...argN` і з даним `functionBody`.
1515

16-
It's easier to understand by looking at an example. Here's a function with two arguments:
16+
Легше зрозуміти, дивлячись на приклад. Ось функція з двома аргументами:
1717

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

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

24-
And here there's a function without arguments, with only the function body:
24+
А це функція без аргументів, лише з тілом функції:
2525

2626
```js run
27-
let sayHi = new Function('alert("Hello")');
27+
let sayHi = new Function('alert("Привіт")');
2828

29-
sayHi(); // Hello
29+
sayHi(); // Привіт
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, in complex web-applications.
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 (we covered that in the chapter <info:closure>).
49+
Зазвичай функція пам’ятає, де вона народилася в спеціальній властивості `[[Environment]]`. Вона посилається на лексичне середовище, звідки функція була створена (ми розглянули це в розділі <info:closure>).
5050

51-
But when a function is created using `new Function`, its `[[Environment]]` is set to reference not the current Lexical Environment, but the global one.
51+
Але коли функція створюється за допомогою `new Function`, її `[[Environment]]` встановлюється так, щоб вказати глобальне лексичне середовище, а не поточне.
5252

53-
So, such function doesn't have access to outer variables, only to the global ones.
53+
Отже, така функція не має доступу до зовнішніх змінних, тільки до глобальних.
5454

5555
```js run
5656
function getFunc() {
57-
let value = "test";
57+
let value = "тест";
5858

5959
*!*
6060
let func = new Function('alert(value)');
@@ -63,14 +63,14 @@ function getFunc() {
6363
return func;
6464
}
6565

66-
getFunc()(); // error: value is not defined
66+
getFunc()(); // Помилка: value не визначено
6767
```
6868

69-
Compare it with the regular behavior:
69+
Порівняйте це зі звичайною поведінкою:
7070

7171
```js run
7272
function getFunc() {
73-
let value = "test";
73+
let value = "тест";
7474

7575
*!*
7676
let func = function() { alert(value); };
@@ -79,45 +79,45 @@ function getFunc() {
7979
return func;
8080
}
8181

82-
getFunc()(); // *!*"test"*/!*, from the Lexical Environment of getFunc
82+
getFunc()(); // *!*"тест"*/!*, з лексичного середовища функції getFunc
8383
```
8484

85-
This special feature of `new Function` looks strange, but appears very useful in practice.
85+
Ця особлива особливість `new Function` виглядає дивно, але на практиці виявляється дуже корисною.
8686

87-
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.
87+
Уявіть собі, що ми повинні створити функцію з рядка. Код цієї функції не відомий під час написання сценарію (ось чому ми не використовуємо звичайні функції), але буде відомий в процесі виконання. Ми можемо отримати його з сервера або з іншого джерела.
8888

89-
Our new function needs to interact with the main script.
89+
Наша нова функція повинна взаємодіяти з основним скриптом.
9090

91-
What if it could access the outer variables?
91+
Що робити, щоб вона могла отримати доступ до зовнішніх змінних?
9292

93-
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.
93+
Проблема полягає в тому, що до відправки JavaScript-коду до сервера реального робочого проєкту, він стискається за допомогою *мініфікатора* -- це спеціальна програма, яка стискає код, видаляючи додаткові коментарі, пробіли та, що важливо, перейменовує локальні змінні короткими іменами.
9494

95-
For instance, if a function has `let userName`, minifier replaces it with `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.
95+
Наприклад, якщо функція має `let userName`, то мініфікатор замінює цей код на `let a` (або іншу букву, якщо ця зайнята) і робить це всюди. Це, як правило, безпечна річ, тому що змінна локальна, нічого поза межами функції не може отримати доступ до неї. І всередині функції, мініфікатор замінює кожне згадування про цю змінну. Мініфікатори розумні, вони аналізують структуру коду, тому вони нічого не порушують. Вони не просто здійснюють "примітивний" пошук-заміну.
9696

97-
So if `new Function` had access to outer variables, it would be unable to find renamed `userName`.
97+
Отже, якщо `new Function` мала доступ до зовнішніх змінних, вона не зможе знайти перейменовану змінну `username`.
9898

99-
**If `new Function` had access to outer variables, it would have problems with minifiers.**
99+
** Якби `new Function` мала доступ до зовнішніх змінних, то вона б мала проблеми з мініфікаторами.**
100100

101-
Besides, such code would be architecturally bad and prone to errors.
101+
Крім того, такий код буде архітектурно поганим і схильним до помилок.
102102

103-
To pass something to a function, created as `new Function`, we should use its arguments.
103+
Щоб передати щось до функції, створеної як `new Function`, ми повинні використовувати її аргументи.
104104

105-
## Summary
105+
## Підсумки
106106

107-
The syntax:
107+
Синтаксис:
108108

109109
```js
110110
let func = new Function ([arg1, arg2, ...argN], functionBody);
111111
```
112112

113-
For historical reasons, arguments can also be given as a comma-separated list.
113+
З історичних причин аргументи також можуть бути надані як список, розділений комами.
114114

115-
These three declarations mean the same:
115+
Ці три оголошення означають одне і те ж:
116116

117117
```js
118-
new Function('a', 'b', 'return a + b'); // basic syntax
119-
new Function('a,b', 'return a + b'); // comma-separated
120-
new Function('a , b', 'return a + b'); // comma-separated with spaces
118+
new Function('a', 'b', 'return a + b'); // основний синтаксис
119+
new Function('a,b', 'return a + b'); // через кому
120+
new Function('a , b', 'return a + b'); // через кому з пробілами
121121
```
122122

123-
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 insures us from errors. Passing parameters explicitly is a much better method architecturally and causes no problems with minifiers.
123+
Функції, створені з `new Function`, мають `[[Environment]]`, що посилається на глобальне лексичне середовище, а не зовнішнє. Отже, вони не можуть використовувати зовнішні змінні. Але це насправді добре, тому що це застраховує нас від помилок. Передача параметрів явно є набагато кращим методом, архітектурно і не викликає проблем з мініфікаторами.

0 commit comments

Comments
 (0)