Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
EzequielCaste merged 13 commits intojavascript-tutorial:masterfrom11joselu:new-function
Jun 16, 2020
Merged
Changes fromall commits
Commits
Show all changes
13 commits
Select commitHold shift + click to select a range
864c942
new-function: translate MD to spanish
11joseluNov 2, 2019
ad45108
new-function: fix some typo issues
11joseluNov 25, 2019
6aeaa82
Merge branch 'master' into new-function
vplentinaxJun 16, 2020
ae90bc2
Update 1-js/06-advanced-functions/07-new-function/article.md
EzequielCasteJun 16, 2020
dd2618c
Update 1-js/06-advanced-functions/07-new-function/article.md
EzequielCasteJun 16, 2020
1c95fe2
Update 1-js/06-advanced-functions/07-new-function/article.md
EzequielCasteJun 16, 2020
3f738d9
Update 1-js/06-advanced-functions/07-new-function/article.md
EzequielCasteJun 16, 2020
431bb77
Update 1-js/06-advanced-functions/07-new-function/article.md
EzequielCasteJun 16, 2020
244f966
Update 1-js/06-advanced-functions/07-new-function/article.md
EzequielCasteJun 16, 2020
85c2e80
Update 1-js/06-advanced-functions/07-new-function/article.md
EzequielCasteJun 16, 2020
62972aa
Update 1-js/06-advanced-functions/07-new-function/article.md
EzequielCasteJun 16, 2020
1eeddda
Update 1-js/06-advanced-functions/07-new-function/article.md
EzequielCasteJun 16, 2020
0859772
Update 1-js/06-advanced-functions/07-new-function/article.md
EzequielCasteJun 16, 2020
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
102 changes: 52 additions & 50 deletions1-js/06-advanced-functions/07-new-function/article.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,123 +1,125 @@
# La sintaxis "new Function"

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

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

## Syntax

The syntax for creating a function:
La sintaxis 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`.
La función se crea con los argumentos `arg1...argN`y el`functionBody` dado.

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
letsumar = new Function('a', 'b', 'return a + b');
letsum = 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 hayargumentos, entonces hay sólo un único argumento,el cuerpo de la función sería:
Y aquí hayuna función sin argumentos, con soloel cuerpo de la función:


```js run
letsayHi = new Function('alert("Hello")');
letdiHola = 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
letdiHola= new Function('alert("Hola")');
letsayHi= 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
Lamayor diferenciasobre lasotrasmaneras de crear funcionesque hemos visto, es que la función se crea literalmentecon un string y es pasada en tiempo de ejecución.
Laprincipal diferenciacon respecto aotrasformasque hemos visto es que la función se crea literalmentea 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 surgeenetapas 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,enaplicaciones 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 outervariables, only to the global ones.
Entonces, dichas funciones no tiene acceso avariables externas, solo a las globales.


```js run
function getFunc() {
letvalue = "test";
letvalor = "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: valoris not defined
getFunc()(); // error: valorno está definido

```

Compare it with the regular behavior:
Compáralo con el comportamiento normal:

```js run
function getFunc() {
letvalue = "test";
letvalor = "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 thescript (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 elscript (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 outervariables?
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 lasvariables 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, renombralas variableslocales a otras más cortas.
¿Qué pasaría si pudiera acceder alas variablesexternas?
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 siesta 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_ reemplazatodo 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, elminifier reemplazacada 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 alasvariables externas,entoncesno 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 encontrarel`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 pasarlealgo ala función creadacon`new Function`, debemospasarle explícitamente como argumento.
Para pasaralgo auna función creadacomo`new Function`, debemosusar 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

To pass something to a function, created as `new Function`, we should use its arguments.
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

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

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

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

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


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

These three declarations mean the same:
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.

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


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:


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


[8]ページ先頭

©2009-2025 Movatter.jp