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

Variable scope#178

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 8 commits intojavascript-tutorial:masterfromvplentinax:variable-scope
Jun 22, 2020
Merged
Show file tree
Hide file tree
Changes fromall 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
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
The answer is: **Pete**.
La respuesta es: **Pete**.

A function gets outer variables as they are now, it uses the most recent values.
Una función obtiene variables externas con su estado actual, y utiliza los valores más recientes.

Los valores de variables anteriores no se guardan en ningún lado. Cuando una función quiere una variable, toma el valor actual de su propio entorno léxico o el externo.

Old variable values are not saved anywhere. When a function wants a variable, it takes the current value from its own Lexical Environment or the outer one.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,9 +2,9 @@ importance: 5

---

#Does a function pickup latest changes?
#¿Una función recoge los últimos cambios?

The function sayHiuses an externalvariablename. When the function runs, which value is it going to use?
La función sayHiusa un nombre devariableexterno. Cuando se ejecuta la función, ¿qué valor va a utilizar?

```js
let name = "John";
Expand All@@ -15,9 +15,10 @@ function sayHi() {

name = "Pete";

sayHi(); // what will it show: "John" or "Pete"?
sayHi(); // ¿qué mostrará: "John" o "Pete"?

```
Tales situaciones son comunes tanto en el desarrollo del navegador como del lado del servidor. Se puede programar que una función se ejecute más tarde de lo que se creó, por ejemplo, después de una acción del usuario o una solicitud de red.

Such situations are common both in browser and server-side development. A function may be scheduled to execute later than it is created, for instance after a user action or a network request.
Entonces, la pregunta es: ¿recoge los últimos cambios?

So, the question is: does it pick up the latest changes?
48 changes: 25 additions & 23 deletions1-js/06-advanced-functions/03-closure/10-make-army/solution.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@

Let's examine what's done inside`makeArmy`,and the solution will become obvious.
Examinemos lo que se hace dentro de`makeArmy`,y la solución será obvia.

1.It creates an emptyarray `shooters`:
1.Crea unarray vacío. `shooters`:

```js
let shooters = [];
```
2. Fills it in the loop via `shooters.push(function...)`.

Every element is a function, so the resulting array looks like this:
2. Lo llena en el bucle a través de `shooters.push(function...)`.

Cada elemento es una función, por lo que el array resultante se ve así:

```js no-beautify
shooters = [
Expand All@@ -24,38 +25,38 @@ Let's examine what's done inside `makeArmy`, and the solution will become obviou
function () { alert(i); }
];
```

3. El array se devuelve desde la función.

3. The array is returned from the function.

Then, later, the call to `army[5]()` will get the element `army[5]` from the array (it will be a function) and call it.
Luego, más tarde, la llamada a `army[5] ()` obtendrá el elemento `army[5]` de el array (será una función) y lo llamará.

Now why all such functions show the same?
Ahora, ¿por qué todas esas funciones muestran lo mismo?

That's because there'snolocalvariable `i`inside`shooter` functions. When such a function is called, it takes`i`from its outer lexical environment.
Esto se debe a quenohay unavariablelocal`i`dentro de las funciones`shooter`. Cuando se llama a tal función, toma`i`de su entorno léxico externo.

What will be the value of `i`?
¿Cuál será el valor de 'i'?

If we look at the source:
Si miramos la fuente:

```js
function makeArmy() {
...
let i = 0;
while (i < 10) {
let shooter = function() { // shooter function
alert( i ); //should show its number
alert( i ); //debería mostrar su número
};
...
}
...
}
```

...We can see that it lives in the lexical environment associated with the current`makeArmy()` run. But when`army[5]()` is called, `makeArmy`has already finished its job, and `i`has the last value: `10` (the end of `while`).
... Podemos ver que vive en el entorno léxico asociado con la ejecución actual de`makeArmy()`. Pero cuando se llama a`army[5]()`, `makeArmy`ya ha terminado su trabajo, y `i`tiene el último valor: `10` (el final de `while`).

As a result, all`shooter`functions get from the outer lexical envrironment the same, last value `i=10`.
Como resultado, todas las funciones`shooter`obtienen del mismo entorno léxico externo, el último valor `i =10`.

We can fix it by moving thevariabledefinition into the loop:
Podemos arreglarlo moviendo la definición devariableal bucle:

```js run demo
function makeArmy() {
Expand All@@ -66,7 +67,7 @@ function makeArmy() {
for(let i = 0; i < 10; i++) {
*/!*
let shooter = function() { // shooter function
alert( i ); //should show its number
alert( i ); //debería mostrar su número
};
shooters.push(shooter);
}
Expand All@@ -80,15 +81,15 @@ army[0](); // 0
army[5](); // 5
```

Now it works correctly, because every time the code block in`for (let i=0...) {...}` is executed, a new Lexical Environment is created for it, with the correspondingvariable `i`.
Ahora funciona correctamente, porque cada vez que se ejecuta el bloque de código en`for (let i = 0...) {...}`, se crea un nuevo entorno léxico para él, con lavariable correspondiente `i`.

So, the value of `i`now lives a little bit closer. Not in`makeArmy()` Lexical Environment, but in the Lexical Environment that corresponds the current loop iteration. That's why now it works.
Entonces, el valor de `i`ahora vive un poco más cerca. No en el entorno léxico`makeArmy()`, sino en el entorno léxico que corresponde a la iteración del bucle actual. Por eso ahora funciona.

![](lexenv-makearmy.svg)

Here we rewrote`while`into `for`.
Aquí reescribimos`while`en `for`.

Another trick could be possible, let's see it for better understanding of the subject:
Podría usarse otro truco, veámoslo para comprender mejor el tema:

```js run
function makeArmy() {
Expand All@@ -100,7 +101,7 @@ function makeArmy() {
let j = i;
*/!*
let shooter = function() { // shooter function
alert( *!*j*/!* ); //should show its number
alert( *!*j*/!* ); //debería verse el núemero
};
shooters.push(shooter);
i++;
Expand All@@ -115,6 +116,7 @@ army[0](); // 0
army[5](); // 5
```

The `while` loop, just like `for`, makes a new Lexical Environment for each run. So here we make sure that it gets the right value for a `shooter`.
El bucle `while`, al igual que `for`, crea un nuevo entorno léxico para cada ejecución. Así que aquí nos aseguramos de que obtenga el valor correcto para un `shooter`.

Copiamos `let j = i`. Esto hace que el cuerpo del bucle sea `j` local y copia el valor de `i` en él. Los primitivos se copian "por valor", por lo que en realidad obtenemos una copia independiente completa de `i`, que pertenece a la iteración del bucle actual.

We copy `let j = i`. This makes a loop body local `j` and copies the value of `i` to it. Primitives are copied "by value", so we actually get a complete independent copy of `i`, belonging to the current loop iteration.
16 changes: 8 additions & 8 deletions1-js/06-advanced-functions/03-closure/10-make-army/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,11 +2,11 @@ importance: 5

---

#Army of functions
#Ejército de funciones

The following code creates an array of `shooters`.
El siguiente código crea una serie de `shooters`.

Every function is meant to output its number. But something is wrong...
Cada función está destinada a generar su número. Pero algo anda mal...

```js run
function makeArmy() {
Expand All@@ -15,7 +15,7 @@ function makeArmy() {
let i = 0;
while (i < 10) {
let shooter = function() { // shooter function
alert( i ); //should show its number
alert( i ); //debería mostrar su número
};
shooters.push(shooter);
i++;
Expand All@@ -26,10 +26,10 @@ function makeArmy() {

let army = makeArmy();

army[0](); //the shooter number 0shows 10
army[5](); // and number 5also outputs 10...
// ...all shooters show10instead of their0, 1, 2, 3...
army[0](); //el tirador número 0muestra 10
army[5](); //y el número 5también produce 10...
// ...todos los tiradores muestran10en lugar de sus0, 1, 2, 3...
```

Why do all of the shooters show the same value? Fix the code so that they work as intended.
¿Por qué todos los tiradores muestran el mismo valor? Arregle el código para que funcionen según lo previsto.

View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
The answer is: **Pete**.

The `work()` function in the code below gets `name` from the place of its origin through the outer lexical environment reference:
La respuesta es: **Pete**.

La función `work()` en el código a continuación obtiene `name` del lugar de su origen a través de la referencia del entorno léxico externo:

![](lexenv-nested-work.svg)

So, the result is `"Pete"` here.
Entonces, el resultado es "Pete".

Pero si no hubiera `let name` en` makeWorker () `, entonces la búsqueda saldría y tomaría la variable global como podemos ver en la cadena de arriba. En ese caso, el resultado sería `John`.

But if there were no `let name` in `makeWorker()`, then the search would go outside and take the global variable as we can see from the chain above. In that case the result would be `"John"`.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,11 +2,11 @@ importance: 5

---

#Which variablesare available?
#¿Qué variablesestán disponibles?

The function `makeWorker`below makes another function and returns it. That new function can be called from somewhere else.
La función `makeWorker`a continuación crea otra función y la devuelve. Esa nueva función se puede llamar desde otro lugar.

Will it have access to the outer variables from its creation place, or the invocation place, or both?
¿Tendrá acceso a las variables externas desde su lugar de creación, o desde el lugar de invocación, o ambos?

```js
function makeWorker() {
Expand All@@ -19,11 +19,11 @@ function makeWorker() {

let name = "John";

//create a function
//crea una función
let work = makeWorker();

//call it
work(); //what will it show?
//la llama
work(); //¿qué mostrará?
```

Which value it will show? "Pete"or "John"?
¿Qué valor mostrará? "Pete"o "John"?
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
The answer: **0,1.**

Functions `counter` and `counter2` are created by different invocations of `makeCounter`.
La respuesta: **0,1.**

Las funciones `counter` y` counter2` son creadas por diferentes invocaciones de `makeCounter`.

Por lo tanto, tienen entornos léxicos externos independientes, cada uno tiene su propio `count`.

So they have independent outer Lexical Environments, each one has its own `count`.
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,11 +2,12 @@ importance: 5

---

#Are counters independent?
#¿Son independientes los contadores?

Here we make two counters: `counter` and `counter2` using the same `makeCounter` function.
Aquí hacemos dos contadores: `counter` y `counter2` usando la misma función `makeCounter`.

¿Son independientes? ¿Qué va a mostrar el segundo contador? `0,1` o `2,3` o algo más?

Are they independent? What is the second counter going to show? `0,1` or `2,3` or something else?

```js
function makeCounter() {
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@

Surely it will work just fine.
Seguramente funcionará bien.

Ambas funciones anidadas se crean dentro del mismo entorno léxico externo, por lo que comparten acceso a la misma variable `count`:

Both nested functions are created within the same outer Lexical Environment, so they share access to the same `count` variable:

```js run
function Counter() {
Expand All@@ -10,7 +11,6 @@ function Counter() {
this.up = function() {
return ++count;
};

this.down = function() {
return --count;
};
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,11 +2,12 @@ importance: 5

---

#Counter object
#Objeto contador

Here a counter object is made with the help of the constructor function.
Aquí se crea un objeto contador con la ayuda de la función constructora.

¿Funcionará? ¿Qué mostrará?

Will it work? What will it show?

```js
function Counter() {
Expand All@@ -26,4 +27,3 @@ alert( counter.up() ); // ?
alert( counter.up() ); // ?
alert( counter.down() ); // ?
```

View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
The result is **an error**.

The function `sayHi` is declared inside the `if`, so it only lives inside it. There is no `sayHi` outside.
El resultado es **un error**.

La función `sayHi` se declara dentro de `if`, por lo que solo vive dentro de ella. No hay `sayHi` afuera.

View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@

#Function in if
#Función en if

Look at the code. What will be the result of the call at the last line?
Mira el código ¿Cuál será el resultado de la llamada en la última línea?

```js run
let phrase = "Hello";
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
For the second parentheses to work, the first ones must return a function.
Para que funcionen los segundos paréntesis, los primeros deben devolver una función.

Like this:
Como esto:

```js run
function sum(a) {

return function(b) {
return a + b; //takes "a"from the outer lexical environment
return a + b; //toma "a"del entorno léxico externo
};

}

alert( sum(1)(2) ); // 3
Expand Down
10 changes: 5 additions & 5 deletions1-js/06-advanced-functions/03-closure/6-closure-sum/task.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,16 +2,16 @@ importance: 4

---

#Sum with closures
#Suma con clausuras

Write function`sum`that works like this: `sum(a)(b) = a+b`.
Escriba la función`sum`que funcione así: `sum(a)(b) = a+b`.

Yes, exactly this way, using double parentheses (not a mistype).
Sí, exactamente de esta manera, usando paréntesis dobles (no es un error de tipeo).

Por ejemeplo:

For instance:

```js
sum(1)(2) = 3
sum(5)(-1) = 4
```

Loading

[8]ページ先頭

©2009-2025 Movatter.jp