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
+
Esiste un ulteriore modo per creare una funzione. E' raramente utilizzato, ma a volte è l'unica alternativa.
5
5
6
-
## Syntax
6
+
## Sintassi
7
7
8
-
The syntax for creating a function:
8
+
La sintassi per la creazione di una funzione con questo metodo è la seguente:
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
+
La funzione viene creata con gli argomenti`arg1...argN`ed il corpo`functionBody`.
15
15
16
-
It's easier to understand by looking at an example. Here's a function with two arguments:
16
+
E' più semplice da comprendere guardando un esempio. Nel seguente abbiamo una funzione con due argomenti:
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
+
In quest'altro esempio, invece, non abbiamo argomenti, c'è solo il corpo della funzione:
25
25
26
26
```js run
27
27
let sayHi =newFunction('alert("Hello")');
28
28
29
29
sayHi(); // Hello
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
+
La differenza dalle altre modalità di creazione funzioni che abbiamo visto, è che qui la funzione viene creata letteralmente da una stringa, che viene passata in fase di esecuzione.
33
33
34
-
All previous declarations required us, programmers, to write the function code in the script.
34
+
Tutte le dichiarazioni di funzione precedenti richiedevano di scrivere il codice della funzione nello script.
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
+
Ma`new Function`ci permette di trasformare qualsiasi stringa in una funzione. Per esempio potremmo ricevere una nuova funzione da un server e quindi eseguirla:
37
37
38
38
```js
39
-
let str =...receive the code from a server dynamically...
39
+
let str =...riceviamo il codice della funzione dinamicamente, da un server...
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
+
Viene utilizzato in casi molto specifici, come quando riceviamo codice da un server, o per compilare dinamicamente una funzione da un modello, in applicazioni web complesse.
46
46
47
-
## Closure
47
+
## Closure (chiusura)
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
+
Di solito, una funzione memorizza dove è nata nella proprietà speciale `[[Environment]]`. Questa fa riferimento al Lexical Environment da cui è stata creata (lo abbiamo trattato nel capitolo<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
+
Ma quando una funzione viene creata con`new Function`, il suo `[[Environment]]`non fa riferimento all'attuale Lexical Environment, ma a quello globale.
52
52
53
-
So, such function doesn't have access to outer variables, only to the global ones.
53
+
Quindi, tale funzione non ha accesso alle variabili esterne, ma solo a quelle globali.
54
54
55
55
```js run
56
56
functiongetFunc() {
@@ -66,7 +66,7 @@ function getFunc() {
66
66
getFunc()(); // error: value is not defined
67
67
```
68
68
69
-
Compare it with the regular behavior:
69
+
Confrontiamolo con il normale comportamento:
70
70
71
71
```js run
72
72
functiongetFunc() {
@@ -79,45 +79,43 @@ function getFunc() {
79
79
return func;
80
80
}
81
81
82
-
getFunc()(); // *!*"test"*/!*, from the Lexical Environment of getFunc
82
+
getFunc()(); // *!*"test"*/!*, dal Lexical Environment di getFunc
83
83
```
84
84
85
-
This special feature of`new Function`looks strange, but appears very useful in practice.
85
+
Questa caratteristica speciale di`new Function`sembra strana, ma si rivela molto utile nella pratica.
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
+
Immaginiamo di dover creare una funzione da una stringa. Il codice di questa funzione è sconosciuto nel momento in cui scriviamo lo script (per questo non usiamo i normali metodi), ma lo conosceremo durante l'esecuzione. Potremmo riceverlo dal server o da un'altra fonte.
88
88
89
-
Our new function needs to interact with the main script.
89
+
La nostra nuova funzione ha bisogno di interagire con lo script principale.
90
90
91
-
What if it could access the outer variables?
91
+
E se potesse accedere alle variabili esterne?
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
+
Il problema è che, prima che JavaScript venga messo in produzione, viene spesso compresso utilizzando un *minifier*, ossia un programma speciale che riduce il codice rimuovendo commenti, spazi e, cosa importante, rinominando le variabili locali utilizzando nomi più brevi.
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
+
Ad esempio, se una funzione contiene`let userName`, il minifier lo sostituisce con`let a` (o con un'altra lettera se questa è già occupata), e lo fa ovunque. Solitamente è una procedura sicura: poiché la variabile è locale, nulla al di fuori della funzione può accedervi. Mentre all'interno della funzione il minifier sostituisce ogni sua menzione. I minifiers sono intelligenti, analizzano la struttura del codice e non rompono nulla. Non sono degli stupidi trova-e-sostituisci.
96
96
97
-
So if`new Function`had access to outer variables, it would be unable to find renamed `userName`.
97
+
Quindi se`new Function`avesse accesso alle variabili esterne, non sarebbe in grado di trovare la variabile`userName` rinominata.
98
98
99
-
**If`new Function`had access to outer variables, it would have problems with minifiers.**
99
+
**Se`new Function`avesse accesso alle variabili esterne, ci sarebbero problemi con i minifiers.**
100
100
101
-
Besides, such code would be architecturally bad and prone to errors.
101
+
Inoltre, tale codice sarebbe pessimo dal punto di vista architetturale e soggetto ad errori.
102
102
103
-
To pass something to a function, created as`new Function`, we should use its arguments.
103
+
Per passare qualcosa a una funzione, creata con`new Function`, dovremmo usare i suoi argomenti.
104
104
105
-
## Summary
105
+
## Riepilogo
106
106
107
-
The syntax:
107
+
La sintassi:
108
108
109
109
```js
110
110
let func =newFunction ([arg1, arg2, ...argN], functionBody);
111
111
```
112
+
Per ragioni storiche, gli argomenti possono anche essere passati come elenco separato da virgole.
112
113
113
-
For historical reasons, arguments can also be given as a comma-separated list.
114
-
115
-
These three declarations mean the same:
114
+
Queste tre dichiarazioni hanno lo stesso significato:
116
115
117
116
```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
117
+
newFunction('a', 'b', 'return a + b'); //sintassi base
118
+
newFunction('a,b', 'return a + b'); //elenco separato da virgola
119
+
newFunction('a , b', 'return a + b'); //elenco separato da virgola e spazio
121
120
```
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.
121
+
Nelle funzioni create con `new Function`, `[[Environment]]` fa riferimento al Lexical Environment globale, non a quello esterno. Quindi queste funzioni non possono utilizzare variabili esterne. In realtà ciò è un bene perché ci mette al riparo da da errori. Passare i parametri in modo esplicito è un metodo migliore dal punto di vista architetturale e non causa problemi con i minifiers.
0 commit comments