Skip to content

Commit 2b91e91

Browse files
committed
The "new Function" syntax
1 parent d2f312b commit 2b91e91

File tree

1 file changed

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

1 file changed

+36
-38
lines changed
Lines changed: 36 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,56 +1,56 @@
11

2-
# The "new Function" syntax
2+
# La sintassi "new Function"
33

4-
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.
55

6-
## Syntax
6+
## Sintassi
77

8-
The syntax for creating a function:
8+
La sintassi per la creazione di una funzione con questo metodo è la seguente:
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+
La funzione viene creata con gli argomenti `arg1...argN` ed il corpo `functionBody`.
1515

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:
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+
In quest'altro esempio, invece, non abbiamo argomenti, c'è solo il corpo della funzione:
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+
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.
3333

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.
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+
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:
3737

3838
```js
39-
let str = ... receive the code from a server dynamically ...
39+
let str = ... riceviamo il codice della funzione dinamicamente, da un server ...
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+
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.
4646

47-
## Closure
47+
## Closure (chiusura)
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+
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>).
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+
Ma quando una funzione viene creata con `new Function`, il suo `[[Environment]]` non fa riferimento all'attuale Lexical Environment, ma a quello globale.
5252

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.
5454

5555
```js run
5656
function getFunc() {
@@ -66,7 +66,7 @@ function getFunc() {
6666
getFunc()(); // error: value is not defined
6767
```
6868

69-
Compare it with the regular behavior:
69+
Confrontiamolo con il normale comportamento:
7070

7171
```js run
7272
function getFunc() {
@@ -79,45 +79,43 @@ function getFunc() {
7979
return func;
8080
}
8181

82-
getFunc()(); // *!*"test"*/!*, from the Lexical Environment of getFunc
82+
getFunc()(); // *!*"test"*/!*, dal Lexical Environment di getFunc
8383
```
8484

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.
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+
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.
8888

89-
Our new function needs to interact with the main script.
89+
La nostra nuova funzione ha bisogno di interagire con lo script principale.
9090

91-
What if it could access the outer variables?
91+
E se potesse accedere alle variabili esterne?
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+
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.
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+
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.
9696

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.
9898

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.**
100100

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.
102102

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.
104104

105-
## Summary
105+
## Riepilogo
106106

107-
The syntax:
107+
La sintassi:
108108

109109
```js
110110
let func = new Function ([arg1, arg2, ...argN], functionBody);
111111
```
112+
Per ragioni storiche, gli argomenti possono anche essere passati come elenco separato da virgole.
112113

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:
116115

117116
```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
117+
new Function('a', 'b', 'return a + b'); // sintassi base
118+
new Function('a,b', 'return a + b'); // elenco separato da virgola
119+
new Function('a , b', 'return a + b'); // elenco separato da virgola e spazio
121120
```
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

Comments
 (0)