Skip to content

Commit 943b805

Browse files
Merge pull request #120 from 11joselu/new-function
The "new Function" syntax
2 parents 5e03906 + 0859772 commit 943b805

File tree

1 file changed

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

1 file changed

+52
-50
lines changed
Lines changed: 52 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,123 +1,125 @@
1+
# La sintaxis "new Function"
12

2-
# The "new Function" syntax
3+
Hay una forma más de crear una función. Raramente se usa, pero a veces no hay alternativa.
34

4-
There's one more way to create a function. It's rarely used, but sometimes there's no alternative.
5+
## Sintaxis
56

6-
## Syntax
7-
8-
The syntax for creating a function:
7+
La sintaxis para crear una función:
98

109
```js
1110
let func = new Function ([arg1, arg2, ...argN], functionBody);
1211
```
1312

14-
The function is created with the arguments `arg1...argN` and the given `functionBody`.
13+
La función se crea con los argumentos `arg1 ... argN` y el `functionBody` dado.
1514

16-
It's easier to understand by looking at an example. Here's a function with two arguments:
15+
Es más fácil entender viendo un ejemplo: Aquí tenemos una función con dos argumentos:
1716

1817
```js run
19-
let sum = new Function('a', 'b', 'return a + b');
20-
21-
alert( sum(1, 2) ); // 3
18+
let sumar = new Function('a', 'b', 'return a + b');
19+
alert(sumar(1, 2)); // 3
2220
```
2321

24-
And here there's a function without arguments, with only the function body:
22+
Si no hay argumentos, entonces hay sólo un único argumento, el cuerpo de la función sería:
2523

2624
```js run
27-
let sayHi = new Function('alert("Hello")');
25+
let diHola = new Function('alert("Hola")');
2826

29-
sayHi(); // Hello
27+
diHola(); // Hola
3028
```
29+
La mayor diferencia sobre las otras maneras de crear funciones que hemos visto, es que la función se crea literalmente con un string y es pasada en tiempo de ejecución.
3130

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.
31+
Las declaraciones anteriores nos obliga a nosotros, los programadores, a escribir el código de la función en el script.
3332

34-
All previous declarations required us, programmers, to write the function code in the script.
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:
33+
Pero `new Function` nos permite convertir cualquier string en una función. Por ejemplo, podemos recibir una nueva función desde el servidor y ejecutarlo.
3734

3835
```js
39-
let str = ... receive the code from a server dynamically ...
36+
let str = ... recibir el código de un servidor dinámicamente ...
4037

4138
let func = new Function(str);
4239
func();
4340
```
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.
41+
Se utilizan en casos muy específicos, como cuando recibimos código de un servidor, o compilar dinámicamente una función a partir de una plantilla. La necesidad surge en etapas avanzadas de desarrollo.
4642

4743
## Closure
4844

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>).
45+
Normalmente, una función recuerda dónde nació en una propiedad especial llamada `[[Environment]]`. Hace referencia al entorno léxico desde dónde se creó.
5046

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.
47+
Pero cuando una función es creada usando `new Function`, su `[[Environment]]` no hace referencia al entorno léxico actual, sino al global.
5248

5349
So, such function doesn't have access to outer variables, only to the global ones.
5450

5551
```js run
5652
function getFunc() {
57-
let value = "test";
53+
let valor = "test";
5854

5955
*!*
60-
let func = new Function('alert(value)');
56+
let func = new Function('alert(valor)');
6157
*/!*
6258

6359
return func;
6460
}
6561

66-
getFunc()(); // error: value is not defined
62+
getFunc()(); // error: valor is not defined
6763
```
6864

69-
Compare it with the regular behavior:
65+
Compáralo con el comportamiento normal:
7066

7167
```js run
7268
function getFunc() {
73-
let value = "test";
69+
let valor = "test";
7470

7571
*!*
76-
let func = function() { alert(value); };
72+
let func = function() { alert(valor); };
7773
*/!*
7874

7975
return func;
8076
}
8177

82-
getFunc()(); // *!*"test"*/!*, from the Lexical Environment of getFunc
78+
getFunc()(); // *!*"test"*/!*, obtenido del entorno léxico de getFunc
8379
```
8480

85-
This special feature of `new Function` looks strange, but appears very useful in practice.
81+
Esta característica especial de `new Function` parece estraño, pero parece muy útil en la práctica.
8682

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.
83+
Imagina que debemos crear una funcion apartir de una string. El código de dicha función no se conoce al momento de escribir el script (es por eso que no usamos funciones regulares), pero se conocerá en el proceso de ejecución. Podemos recibirlo del servidor o de otra fuente.
8884

89-
Our new function needs to interact with the main script.
85+
¿Quizás queremos que pueda acceder a las variables locales externas?
9086

91-
What if it could access the outer variables?
87+
El problema es que antes de publicar el JavaScript a producción, este es comprimido usando un _minifier_ -- un programa especial que comprime código elimiando los comentarios extras, espacios -- y lo que es más importante, renombra las variables locales a otras más cortas.
9288

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.
89+
Por ejemplo, si una función tiene `let userName`, el _minifier_ lo reemplaza a `let a` (o otra letra si esta está siendo utilizada), y lo hace en todas partes. Esto es normalmente una práctica segura, al ser una variable local, nada de fuera de la función puede acceder a ella. Y dentro de una función, el _minifier_ reemplaza todo lo que le menciona. Los Minificadores son inteligiente, ellos analizan la estructura del código, por lo tanto, no rompen nada. No realizan un simple buscar y reemplazar.
9490

95-
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.
91+
Pero, si `new Function` puede acceder a las variables externas, entonces no podría encontrar `userName`, ya que esto es pasada como un string _después_ de que el código haya sido minificado.
9692

97-
So if `new Function` had access to outer variables, it would be unable to find renamed `userName`.
93+
**Incluso si podemos acceder al entorno léxico con `new Function`, tendríamos problemas con los minificadores**
9894

99-
**If `new Function` had access to outer variables, it would have problems with minifiers.**
95+
La "característica especial" de `new Function` nos salva de errores.
10096

101-
Besides, such code would be architecturally bad and prone to errors.
97+
Y obliga a un mejor código. Si necesitamos pasarle algo a la función creada con `new Function`, debemos pasarle explícitamente como argumento.
10298

103-
To pass something to a function, created as `new Function`, we should use its arguments.
99+
Nuestra función "suma" lo hace bien:
104100

105-
## Summary
101+
```js run
102+
*!*
103+
let suma = new Function('a', 'b', 'return a + b');
104+
*/!*
106105

107-
The syntax:
106+
let a = 1, b = 2;
108107

109-
```js
110-
let func = new Function ([arg1, arg2, ...argN], functionBody);
108+
*!*
109+
// outer values are passed as arguments
110+
alert( sum(a, b) ); // 3
111+
*/!*
111112
```
113+
## Resumen
112114

113-
For historical reasons, arguments can also be given as a comma-separated list.
114-
115-
These three declarations mean the same:
115+
La sintáxis:
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+
let func = new Function ([arg1, arg2, ...argN], functionBody);
121119
```
120+
Por razones históricas, los argumentos también pueden ser pasados como una lista separada por comas.
121+
122+
Estos tres significan lo mismo:
122123

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.
124+
```js
125+
new Function('a', 'b', 'return a + b'); // sintáxis básica

0 commit comments

Comments
 (0)