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
There's one more way to create a function. It's rarely used, but sometimes there's no alternative.
4
+
Є ще один спосіб створити функцію. Він рідко використовується, але йому немає альтернативи.
5
5
6
-
## Syntax
6
+
## Синтаксис
7
7
8
-
The syntax for creating a function:
8
+
Синтаксис для створення функції:
9
9
10
10
```js
11
11
let func =newFunction ([arg1, arg2, ...argN], functionBody);
12
12
```
13
13
14
-
The function is created with the arguments `arg1...argN`and the given`functionBody`.
14
+
Функція створюється з аргументами `arg1...argN`і з даним`functionBody`.
15
15
16
-
It's easier to understand by looking at an example. Here's a function with two arguments:
16
+
Легше зрозуміти, дивлячись на приклад. Ось функція з двома аргументами:
17
17
18
18
```js run
19
19
let sum =newFunction('a', 'b', 'return a + b');
20
20
21
21
alert( sum(1, 2) ); // 3
22
22
```
23
23
24
-
And here there's a function without arguments, with only the function body:
24
+
А це функція без аргументів, лише з тілом функції:
25
25
26
26
```js run
27
-
let sayHi =newFunction('alert("Hello")');
27
+
let sayHi =newFunction('alert("Привіт")');
28
28
29
-
sayHi(); //Hello
29
+
sayHi(); //Привіт
30
30
```
31
31
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
+
Основна відмінність від інших способів, які ми бачили, полягає в тому, що функція буквально створюється з рядка, який передається під час виконання.
33
33
34
-
All previous declarations required us, programmers, to write the function code in the script.
34
+
Всі попередні оголошення вимагали нас, програмістів, написати код функції у скрипті.
35
35
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`дозволяє перетворити будь-який рядок у функцію. Наприклад, ми можемо отримати нову функцію з сервера, а потім виконати її:
37
37
38
38
```js
39
-
let str =...receive the code from a server dynamically...
39
+
let str =...код, який отриманий від сервера динамічно...
40
40
41
41
let func =newFunction(str);
42
42
func();
43
43
```
44
44
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
+
Це використовується в дуже специфічних випадках, як, коли ми отримуємо код з сервера, або для динамічної компіляції функцію з шаблону, у складних вебдодатках.
46
46
47
-
## Closure
47
+
## Замикання
48
48
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>).
50
50
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]]`встановлюється так, щоб вказати глобальне лексичне середовище, а не поточне.
52
52
53
-
So, such function doesn't have access to outer variables, only to the global ones.
53
+
Отже, така функція не має доступу до зовнішніх змінних, тільки до глобальних.
54
54
55
55
```js run
56
56
functiongetFunc() {
57
-
let value ="test";
57
+
let value ="тест";
58
58
59
59
*!*
60
60
let func =newFunction('alert(value)');
@@ -63,14 +63,14 @@ function getFunc() {
63
63
return func;
64
64
}
65
65
66
-
getFunc()(); //error: value is not defined
66
+
getFunc()(); //Помилка: value не визначено
67
67
```
68
68
69
-
Compare it with the regular behavior:
69
+
Порівняйте це зі звичайною поведінкою:
70
70
71
71
```js run
72
72
functiongetFunc() {
73
-
let value ="test";
73
+
let value ="тест";
74
74
75
75
*!*
76
76
letfunc=function() { alert(value); };
@@ -79,45 +79,45 @@ function getFunc() {
79
79
return func;
80
80
}
81
81
82
-
getFunc()(); // *!*"test"*/!*, from the Lexical Environment of getFunc
82
+
getFunc()(); // *!*"тест"*/!*, з лексичного середовища функції getFunc
83
83
```
84
84
85
-
This special feature of `new Function`looks strange, but appears very useful in practice.
85
+
Ця особлива особливість `new Function`виглядає дивно, але на практиці виявляється дуже корисною.
86
86
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
+
Уявіть собі, що ми повинні створити функцію з рядка. Код цієї функції не відомий під час написання сценарію (ось чому ми не використовуємо звичайні функції), але буде відомий в процесі виконання. Ми можемо отримати його з сервера або з іншого джерела.
88
88
89
-
Our new function needs to interact with the main script.
89
+
Наша нова функція повинна взаємодіяти з основним скриптом.
90
90
91
-
What if it could access the outer variables?
91
+
Що робити, щоб вона могла отримати доступ до зовнішніх змінних?
92
92
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-коду до сервера реального робочого проєкту, він стискається за допомогою *мініфікатора* -- це спеціальна програма, яка стискає код, видаляючи додаткові коментарі, пробіли та, що важливо, перейменовує локальні змінні короткими іменами.
94
94
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` (або іншу букву, якщо ця зайнята) і робить це всюди. Це, як правило, безпечна річ, тому що змінна локальна, нічого поза межами функції не може отримати доступ до неї. І всередині функції, мініфікатор замінює кожне згадування про цю змінну. Мініфікатори розумні, вони аналізують структуру коду, тому вони нічого не порушують. Вони не просто здійснюють "примітивний" пошук-заміну.
96
96
97
-
So if`new Function`had access to outer variables, it would be unable to find renamed `userName`.
97
+
Отже, якщо`new Function`мала доступ до зовнішніх змінних, вона не зможе знайти перейменовану змінну `username`.
98
98
99
-
**If `new Function`had access to outer variables, it would have problems with minifiers.**
99
+
** Якби `new Function`мала доступ до зовнішніх змінних, то вона б мала проблеми з мініфікаторами.**
100
100
101
-
Besides, such code would be architecturally bad and prone to errors.
101
+
Крім того, такий код буде архітектурно поганим і схильним до помилок.
102
102
103
-
To pass something to a function, created as`new Function`, we should use its arguments.
103
+
Щоб передати щось до функції, створеної як`new Function`, ми повинні використовувати її аргументи.
104
104
105
-
## Summary
105
+
## Підсумки
106
106
107
-
The syntax:
107
+
Синтаксис:
108
108
109
109
```js
110
110
let func =newFunction ([arg1, arg2, ...argN], functionBody);
111
111
```
112
112
113
-
For historical reasons, arguments can also be given as a comma-separated list.
113
+
З історичних причин аргументи також можуть бути надані як список, розділений комами.
114
114
115
-
These three declarations mean the same:
115
+
Ці три оголошення означають одне і те ж:
116
116
117
117
```js
118
-
newFunction('a', 'b', 'return a + b'); //basic syntax
119
-
newFunction('a,b', 'return a + b'); //comma-separated
120
-
newFunction('a , b', 'return a + b'); //comma-separated with spaces
118
+
newFunction('a', 'b', 'return a + b'); //основний синтаксис
119
+
newFunction('a,b', 'return a + b'); //через кому
120
+
newFunction('a , b', 'return a + b'); //через кому з пробілами
121
121
```
122
122
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