|
| 1 | +# La sintaxis "new Function" |
1 | 2 |
|
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. |
3 | 4 |
|
4 |
| -There's one more way to create a function. It's rarely used, but sometimes there's no alternative. |
| 5 | +## Sintaxis |
5 | 6 |
|
6 |
| -## Syntax |
7 |
| - |
8 |
| -The syntax for creating a function: |
| 7 | +La sintaxis para crear una función: |
9 | 8 |
|
10 | 9 | ```js
|
11 | 10 | let func = new Function ([arg1, arg2, ...argN], functionBody);
|
12 | 11 | ```
|
13 | 12 |
|
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. |
15 | 14 |
|
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: |
17 | 16 |
|
18 | 17 | ```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 |
22 | 20 | ```
|
23 | 21 |
|
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: |
25 | 23 |
|
26 | 24 | ```js run
|
27 |
| -let sayHi = new Function('alert("Hello")'); |
| 25 | +let diHola = new Function('alert("Hola")'); |
28 | 26 |
|
29 |
| -sayHi(); // Hello |
| 27 | +diHola(); // Hola |
30 | 28 | ```
|
| 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. |
31 | 30 |
|
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. |
33 | 32 |
|
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. |
37 | 34 |
|
38 | 35 | ```js
|
39 |
| -let str = ... receive the code from a server dynamically ... |
| 36 | +let str = ... recibir el código de un servidor dinámicamente ... |
40 | 37 |
|
41 | 38 | let func = new Function(str);
|
42 | 39 | func();
|
43 | 40 | ```
|
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. |
46 | 42 |
|
47 | 43 | ## Closure
|
48 | 44 |
|
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ó. |
50 | 46 |
|
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. |
52 | 48 |
|
53 | 49 | So, such function doesn't have access to outer variables, only to the global ones.
|
54 | 50 |
|
55 | 51 | ```js run
|
56 | 52 | function getFunc() {
|
57 |
| - let value = "test"; |
| 53 | + let valor = "test"; |
58 | 54 |
|
59 | 55 | *!*
|
60 |
| - let func = new Function('alert(value)'); |
| 56 | + let func = new Function('alert(valor)'); |
61 | 57 | */!*
|
62 | 58 |
|
63 | 59 | return func;
|
64 | 60 | }
|
65 | 61 |
|
66 |
| -getFunc()(); // error: value is not defined |
| 62 | +getFunc()(); // error: valor is not defined |
67 | 63 | ```
|
68 | 64 |
|
69 |
| -Compare it with the regular behavior: |
| 65 | +Compáralo con el comportamiento normal: |
70 | 66 |
|
71 | 67 | ```js run
|
72 | 68 | function getFunc() {
|
73 |
| - let value = "test"; |
| 69 | + let valor = "test"; |
74 | 70 |
|
75 | 71 | *!*
|
76 |
| - let func = function() { alert(value); }; |
| 72 | + let func = function() { alert(valor); }; |
77 | 73 | */!*
|
78 | 74 |
|
79 | 75 | return func;
|
80 | 76 | }
|
81 | 77 |
|
82 |
| -getFunc()(); // *!*"test"*/!*, from the Lexical Environment of getFunc |
| 78 | +getFunc()(); // *!*"test"*/!*, obtenido del entorno léxico de getFunc |
83 | 79 | ```
|
84 | 80 |
|
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. |
86 | 82 |
|
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. |
88 | 84 |
|
89 |
| -Our new function needs to interact with the main script. |
| 85 | +¿Quizás queremos que pueda acceder a las variables locales externas? |
90 | 86 |
|
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. |
92 | 88 |
|
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. |
94 | 90 |
|
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. |
96 | 92 |
|
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** |
98 | 94 |
|
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. |
100 | 96 |
|
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. |
102 | 98 |
|
103 |
| -To pass something to a function, created as `new Function`, we should use its arguments. |
| 99 | +Nuestra función "suma" lo hace bien: |
104 | 100 |
|
105 |
| -## Summary |
| 101 | +```js run |
| 102 | +*!* |
| 103 | +let suma = new Function('a', 'b', 'return a + b'); |
| 104 | +*/!* |
106 | 105 |
|
107 |
| -The syntax: |
| 106 | +let a = 1, b = 2; |
108 | 107 |
|
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 | +*/!* |
111 | 112 | ```
|
| 113 | +## Resumen |
112 | 114 |
|
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: |
116 | 116 |
|
117 | 117 | ```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); |
121 | 119 | ```
|
| 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: |
122 | 123 |
|
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