Skip to content

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

Merged
merged 13 commits into from
Jun 16, 2020
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 56 additions & 48 deletions 1-js/06-advanced-functions/07-new-function/article.md
Original file line number Diff line number Diff line change
@@ -1,123 +1,131 @@
# La sintáxis "new Function"

# The "new Function" syntax
Existe más de una manera de crear una función. Raramente usada, pero en ocasiones no tenemos otra alternativa.

There's one more way to create a function. It's rarely used, but sometimes there's no alternative.
## Sintáxis

## Syntax

The syntax for creating a function:
La sintáxis para crear una función:

```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

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');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
let sumar = new Function('a', 'b', 'return a + b');
let sum = new Function('a', 'b', 'return a + b');
alert( sum(1, 2) ); // 3

alert(sumar(1, 2)); // 3
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
alert(sumar(1, 2)); // 3

```

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:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Si no hay argumentos, entonces hay sólo un único argumento, el cuerpo de la función sería:
Y aquí hay una función sin argumentos, con solo el cuerpo de la función:


```js run
let sayHi = new Function('alert("Hello")');
let diHola = new Function('alert("Hola")');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
let diHola = new Function('alert("Hola")');
let sayHi= new Function('alert("Hola")');


sayHi(); // Hello
diHola(); // Hola
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
diHola(); // Hola
sayHi(); // Hola

```
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.
Copy link
Contributor

Choose a reason for hiding this comment

The 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.
La principal diferencia con respecto a otras formas que hemos visto es que la función se crea literalmente a partir de una cadena, que se pasa en tiempo de ejecución.

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.

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.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
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.
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:


```js
let str = ... receive the code from a server dynamically ...
let str = ... recibir el código de un servidor dinámicamente ...
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
let str = ... recibir el código de un servidor dinámicamente ...
let str = ... recibe el código de un servidor dinámicamente ...


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.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
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.
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, en aplicaciones web complejas.


## 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ó.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
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ó.
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ó (Cubrimos eso en el capítulo <info:closure>).


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.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
So, such function doesn't have access to outer variables, only to the global ones.
Entonces, dichas funciones no tiene acceso a variables externas, solo a las globales.


```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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
getFunc()(); // error: valor is not defined
getFunc()(); // error: valor no está definido

```

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.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Esta característica especial de `new Function` parece estraño, pero parece muy útil en la práctica.
Esta característica especial de `new Function` se ve extraña, pero parece muy útil en la práctica.


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?
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
¿Quizás queremos que pueda acceder a las variables locales externas?
Nuestra nueva función necesita interactuar con el script principal.


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.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
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.
¿Qué pasaría si pudiera acceder a las variables externas?
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.


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.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
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.
Por ejemplo, si una función tiene `let userName`, el *minifier* lo reemplaza a `let a` (o otra letra si ésta 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 cada mención de ello. Los Minificadores son inteligiente, analizan la estructura del código, por lo tanto, no rompen nada. No realizan un simple buscar y reemplazar.


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.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
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.
Entonces, si `new Function` tuviera acceso a variables externas, no podría encontrar el `userName` renombrado.


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**
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
**Incluso si podemos acceder al entorno léxico con `new Function`, tendríamos problemas con los minificadores**
** Si `new Function` tuviera acceso a variables externas, tendría problemas con los minificadores. **


**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.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
La "característica especial" de `new Function` nos salva de errores.
Además, dicho código sería arquitectónicamente malo y propenso a errores.


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.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
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.
Para pasar algo a una función creada como `new Function`, debemos usar sus argumentos.


Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change

Nuestra función "suma" lo hace bien:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Nuestra función "suma" lo hace bien:
## Resumen


Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change

```js run
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
```js run
La sintaxis:

*!*
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
*!*

let suma = new Function('a', 'b', 'return a + b');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
let suma = new Function('a', 'b', 'return a + b');
```js
let func = new Function ([arg1, arg2, ...argN], functionBody);

*/!*
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
*/!*


Copy link
Contributor

Choose a reason for hiding this comment

The 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;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
let a = 1, b = 2;


Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Por razones históricas, los argumentos también se pueden dar como una lista separada por comas.

## Summary
*!*
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
*!*

// outer values are passed as arguments
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// outer values are passed as arguments
Estas tres declaraciones significan lo mismo:

alert( sum(a, b) ); // 3
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
alert( sum(a, b) ); // 3

*/!*
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
*/!*
```js

```
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
```
new Function('a', 'b', 'return a + b'); // syntaxis básica
new Function('a,b', 'return a + b'); // separada por coma
new Function('a , b', 'return a + b'); // separada por coma con espacios

## Resumen
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
## Resumen


The syntax:
La sintáxis:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
La sintáxis:


```js
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
```js
Las funciones creadas con `new Function`, tienen `[[Environment]]` haciendo referencia al entorno léxico global, no al exterior. Por lo tanto, no pueden usar variables externas. Pero eso es realmente bueno, porque nos asegura de los errores. Pasar parámetros explícitamente es un método mucho mejor arquitectónicamente y no causa problemas con los minificadores.

let func = new Function ([arg1, arg2, ...argN], functionBody);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
let func = new Function ([arg1, arg2, ...argN], functionBody);

```
Copy link
Contributor

Choose a reason for hiding this comment

The 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.
Copy link
Contributor

Choose a reason for hiding this comment

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


For historical reasons, arguments can also be given as a comma-separated list.

These three declarations mean the same:
Estos tres significan lo mismo:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Estos tres significan lo mismo:


```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
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
new Function('a', 'b', 'return a + b'); // sintáxis básica

new Function('a,b', 'return a + b'); // separados por coma
new Function('a , b', 'return a + b'); // separados por coma y espacios
```

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.