-
Notifications
You must be signed in to change notification settings - Fork 228
The "new Function" syntax #120
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 3 commits
864c942
ad45108
6aeaa82
ae90bc2
dd2618c
1c95fe2
3f738d9
431bb77
244f966
85c2e80
62972aa
1eeddda
0859772
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||||||||
---|---|---|---|---|---|---|---|---|---|---|
@@ -1,123 +1,131 @@ | ||||||||||
# La sintáxis "new Function" | ||||||||||
EzequielCaste marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||||
|
||||||||||
# The "new Function" syntax | ||||||||||
Existe más de una manera de crear una función. Raramente usada, pero en ocasiones no tenemos otra alternativa. | ||||||||||
EzequielCaste marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||||
|
||||||||||
There's one more way to create a function. It's rarely used, but sometimes there's no alternative. | ||||||||||
## Sintáxis | ||||||||||
EzequielCaste marked this conversation as resolved.
Show resolved
Hide resolved
EzequielCaste marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||||
|
||||||||||
## Syntax | ||||||||||
|
||||||||||
The syntax for creating a function: | ||||||||||
La sintáxis para crear una función: | ||||||||||
EzequielCaste marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||||
|
||||||||||
```js | ||||||||||
let func = new Function ([arg1, arg2, ...argN], functionBody); | ||||||||||
``` | ||||||||||
|
||||||||||
The function is created with the arguments `arg1...argN` and the given `functionBody`. | ||||||||||
En otras palabras, los parámetros de la función (o, para ser más precisos, los nombres de los parámetros) van primero, y luego el cuerpo de la función. Todos los argumentos son de tipo strings | ||||||||||
EzequielCaste marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||||
|
||||||||||
It's easier to understand by looking at an example. Here's a function with two arguments: | ||||||||||
Es más fácil entender viendo un ejemplo: Aquí tenemos una función con dos argumentos: | ||||||||||
|
||||||||||
```js run | ||||||||||
let sum = new Function('a', 'b', 'return a + b'); | ||||||||||
|
||||||||||
alert( sum(1, 2) ); // 3 | ||||||||||
let sumar = new Function('a', 'b', 'return a + b'); | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
alert(sumar(1, 2)); // 3 | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
``` | ||||||||||
|
||||||||||
And here there's a function without arguments, with only the function body: | ||||||||||
Si no hay argumentos, entonces hay sólo un único argumento, el cuerpo de la función sería: | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
|
||||||||||
```js run | ||||||||||
let sayHi = new Function('alert("Hello")'); | ||||||||||
let diHola = new Function('alert("Hola")'); | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
|
||||||||||
sayHi(); // Hello | ||||||||||
diHola(); // Hola | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
``` | ||||||||||
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. | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
no se crea "con un string" sino "a partir de una cadena" |
||||||||||
|
||||||||||
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. | ||||||||||
Las declaraciones anteriores nos obliga a nosotros, los programadores, a escribir el código de la función en el script. | ||||||||||
EzequielCaste marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||||
|
||||||||||
All previous declarations required us, programmers, to write the function code in the script. | ||||||||||
|
||||||||||
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: | ||||||||||
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. | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
|
||||||||||
```js | ||||||||||
let str = ... receive the code from a server dynamically ... | ||||||||||
let str = ... recibir el código de un servidor dinámicamente ... | ||||||||||
EzequielCaste marked this conversation as resolved.
Show resolved
Hide resolved
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
|
||||||||||
let func = new Function(str); | ||||||||||
func(); | ||||||||||
``` | ||||||||||
|
||||||||||
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. | ||||||||||
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. | ||||||||||
EzequielCaste marked this conversation as resolved.
Show resolved
Hide resolved
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
|
||||||||||
## Closure | ||||||||||
|
||||||||||
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>). | ||||||||||
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ó. | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
|
||||||||||
But when a function is created using `new Function`, its `[[Environment]]` is set to reference not the current Lexical Environment, but the global one. | ||||||||||
Pero cuando una función es creada usando `new Function`, su `[[Environment]]` no hace referencia al entorno léxico actual, sino al global. | ||||||||||
|
||||||||||
So, such function doesn't have access to outer variables, only to the global ones. | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
|
||||||||||
```js run | ||||||||||
function getFunc() { | ||||||||||
let value = "test"; | ||||||||||
let valor = "test"; | ||||||||||
|
||||||||||
*!* | ||||||||||
let func = new Function('alert(value)'); | ||||||||||
let func = new Function('alert(valor)'); | ||||||||||
*/!* | ||||||||||
|
||||||||||
return func; | ||||||||||
} | ||||||||||
|
||||||||||
getFunc()(); // error: value is not defined | ||||||||||
getFunc()(); // error: valor is not defined | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
``` | ||||||||||
|
||||||||||
Compare it with the regular behavior: | ||||||||||
Compáralo con el comportamiento normal: | ||||||||||
|
||||||||||
```js run | ||||||||||
function getFunc() { | ||||||||||
let value = "test"; | ||||||||||
let valor = "test"; | ||||||||||
|
||||||||||
*!* | ||||||||||
let func = function() { alert(value); }; | ||||||||||
let func = function() { alert(valor); }; | ||||||||||
*/!* | ||||||||||
|
||||||||||
return func; | ||||||||||
} | ||||||||||
|
||||||||||
getFunc()(); // *!*"test"*/!*, from the Lexical Environment of getFunc | ||||||||||
getFunc()(); // *!*"test"*/!*, obtenido del entorno léxico de getFunc | ||||||||||
``` | ||||||||||
|
||||||||||
This special feature of `new Function` looks strange, but appears very useful in practice. | ||||||||||
Esta característica especial de `new Function` parece estraño, pero parece muy útil en la práctica. | ||||||||||
EzequielCaste marked this conversation as resolved.
Show resolved
Hide resolved
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
|
||||||||||
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. | ||||||||||
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. | ||||||||||
|
||||||||||
Our new function needs to interact with the main script. | ||||||||||
¿Quizás queremos que pueda acceder a las variables locales externas? | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
|
||||||||||
What if it could access the outer variables? | ||||||||||
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. | ||||||||||
EzequielCaste marked this conversation as resolved.
Show resolved
Hide resolved
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
|
||||||||||
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. | ||||||||||
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. | ||||||||||
EzequielCaste marked this conversation as resolved.
Show resolved
Hide resolved
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
|
||||||||||
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. | ||||||||||
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. | ||||||||||
EzequielCaste marked this conversation as resolved.
Show resolved
Hide resolved
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
|
||||||||||
So if `new Function` had access to outer variables, it would be unable to find renamed `userName`. | ||||||||||
**Incluso si podemos acceder al entorno léxico con `new Function`, tendríamos problemas con los minificadores** | ||||||||||
EzequielCaste marked this conversation as resolved.
Show resolved
Hide resolved
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
|
||||||||||
**If `new Function` had access to outer variables, it would have problems with minifiers.** | ||||||||||
La "característica especial" de `new Function` nos salva de errores. | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
|
||||||||||
Besides, such code would be architecturally bad and prone to errors. | ||||||||||
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. | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
|
||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
Nuestra función "suma" lo hace bien: | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
|
||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
```js run | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
*!* | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
let suma = new Function('a', 'b', 'return a + b'); | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
*/!* | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
|
||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
To pass something to a function, created as `new Function`, we should use its arguments. | ||||||||||
let a = 1, b = 2; | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
|
||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
## Summary | ||||||||||
*!* | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
// outer values are passed as arguments | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
alert( sum(a, b) ); // 3 | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
*/!* | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
``` | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
## Resumen | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
|
||||||||||
The syntax: | ||||||||||
La sintáxis: | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
|
||||||||||
```js | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
let func = new Function ([arg1, arg2, ...argN], functionBody); | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
``` | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
Por razones históricas, los argumentos también pueden ser pasados como una lista separada por comas. | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
|
||||||||||
For historical reasons, arguments can also be given as a comma-separated list. | ||||||||||
|
||||||||||
These three declarations mean the same: | ||||||||||
Estos tres significan lo mismo: | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
|
||||||||||
```js | ||||||||||
new Function('a', 'b', 'return a + b'); // basic syntax | ||||||||||
new Function('a,b', 'return a + b'); // comma-separated | ||||||||||
new Function('a , b', 'return a + b'); // comma-separated with spaces | ||||||||||
new Function('a', 'b', 'return a + b'); // sintáxis básica | ||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||
new Function('a,b', 'return a + b'); // separados por coma | ||||||||||
EzequielCaste marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||||
new Function('a , b', 'return a + b'); // separados por coma y espacios | ||||||||||
EzequielCaste marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||||
``` | ||||||||||
EzequielCaste marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||||
|
||||||||||
EzequielCaste marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||||
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. | ||||||||||
Las funciones creadas con `new Function`, tienen un `[[Environment]]` que hace referencia al entorno léxico global, no al exterior. Por lo tanto, no pueden usar las variables externas. Pero en realidad eso es bueno, porque nos salva de errores. Pasar parámetros explícitamente es un método mucho mejor arquitectónicamente y no provoca problemas con los minificadores. | ||||||||||
EzequielCaste marked this conversation as resolved.
Show resolved
Hide resolved
|
||||||||||
|
Uh oh!
There was an error while loading. Please reload this page.