Skip to content

Commit 17864bb

Browse files
authored
Merge pull request #304 from maksumi/referenceType
Reference Type
2 parents a5f8b88 + af64ee5 commit 17864bb

File tree

6 files changed

+70
-72
lines changed

6 files changed

+70
-72
lines changed
Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,29 @@
1-
**Error**!
1+
¡**Error**!
22

3-
Try it:
3+
Inténtalo:
44

55
```js run
66
let user = {
77
name: "John",
88
go: function() { alert(this.name) }
99
}
1010

11-
(user.go)() // error!
11+
(user.go)() // ¡Error!
1212
```
1313

14-
The error message in most browsers does not give us much of a clue about what went wrong.
14+
El mensaje de error en la mayoría de los navegadores no nos da una pista sobre lo que salió mal.
1515

16-
**The error appears because a semicolon is missing after `user = {...}`.**
16+
**El error aparece porque falta un punto y coma después de `user = {...}`.**
1717

18-
JavaScript does not auto-insert a semicolon before a bracket `(user.go)()`, so it reads the code like:
18+
JavaScript no inserta automáticamente un punto y coma antes de un paréntesis `(user.go)()`, por lo que lee el código así:
1919

2020
```js no-beautify
2121
let user = { go:... }(user.go)()
2222
```
2323

24-
Then we can also see that such a joint expression is syntactically a call of the object `{ go: ... }` as a function with the argument `(user.go)`. And that also happens on the same line with `let user`, so the `user` object has not yet even been defined, hence the error.
24+
Entonces también podemos ver que tal expresión conjunta es sintácticamente una llamada del objeto `{ go: ... }` como una función con el argumento `(user.go)`. Y eso también ocurre en la misma línea con `let user`, por lo que el objeto `user` aún no se ha definido y de ahí el error.
2525

26-
If we insert the semicolon, all is fine:
26+
Si insertamos el punto y coma todo está bien:
2727

2828
```js run
2929
let user = {
@@ -34,4 +34,4 @@ let user = {
3434
(user.go)() // John
3535
```
3636

37-
Please note that parentheses around `(user.go)` do nothing here. Usually they setup the order of operations, but here the dot `.` works first anyway, so there's no effect. Only the semicolon thing matters.
37+
Tenga en cuenta que los paréntesis alrededor de `(user.go)` no hacen nada aquí. Usualmente son configurados para ordenar las operaciones, pero aquí el punto `.` funciona primero de todas formas, por lo que no tienen ningún efecto en él. Solamente el punto y coma importa.

1-js/99-js-misc/04-reference-type/2-check-syntax/task.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ importance: 2
22

33
---
44

5-
# Syntax check
5+
# Verificación de sintaxis
66

7-
What is the result of this code?
7+
¿Cuál es el resultado de este código?
88

99

1010
```js no-beautify
@@ -16,4 +16,4 @@ let user = {
1616
(user.go)()
1717
```
1818

19-
P.S. There's a pitfall :)
19+
P.D. Hay una trampa :)
Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,20 @@
11

2-
Here's the explanations.
2+
Aquí está la explicación.
33

4-
1. That's a regular object method call.
4+
1. Esta es una llamada común al método del objeto
5+
2. Lo mismo, aquí los paréntesis no cambian el orden de las operaciones, el punto es el primero de todos modos.
56

6-
2. The same, parentheses do not change the order of operations here, the dot is first anyway.
7-
8-
3. Here we have a more complex call `(expression).method()`. The call works as if it were split into two lines:
7+
3. Aquí tenemos una llamada más compleja `(expression).method()`. La llamada funciona como si se dividiera en dos líneas:
98

109
```js no-beautify
11-
f = obj.go; // calculate the expression
12-
f(); // call what we have
10+
f = obj.go; // Calcula la expresión
11+
f(); // Llama a lo que tenemos
1312
```
1413

15-
Here `f()` is executed as a function, without `this`.
16-
17-
4. The similar thing as `(3)`, to the left of the dot `.` we have an expression.
14+
Aquí `f()` se ejecuta como una función, sin `this`.
1815

19-
To explain the behavior of `(3)` and `(4)` we need to recall that property accessors (dot or square brackets) return a value of the Reference Type.
16+
4. Lo mismo que `(3)`, a la izquierda del punto `.` tenemos una expresión.
2017

21-
Any operation on it except a method call (like assignment `=` or `||`) turns it into an ordinary value, which does not carry the information allowing to set `this`.
18+
Para explicar el funcionamiento de `(3)` y `(4)` necesitamos recordar que los accesores de propiedad (punto o corchetes) devuelven un valor del Tipo de Referencia.
2219

20+
Cualquier operación en él excepto una llamada al método (como asignación `=` o `||`) lo convierte en un valor ordinario que no transporta la información que permite establecer `this`.

1-js/99-js-misc/04-reference-type/3-why-this/task.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@ importance: 3
22

33
---
44

5-
# Explain the value of "this"
5+
# Explica el valor de "this"
66

7-
In the code below we intend to call `obj.go()` method 4 times in a row.
7+
En el código siguiente intentamos llamar al método `obj.go()` 4 veces seguidas.
88

9-
But calls `(1)` and `(2)` works differently from `(3)` and `(4)`. Why?
9+
Pero las llamadas `(1)` y `(2)` funcionan diferente a `(3)` y `(4)`. ¿Por qué?
1010

1111
```js run no-beautify
1212
let obj, method;
Lines changed: 44 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11

2-
# Reference Type
2+
# Tipo de Referencia
33

4-
```warn header="In-depth language feature"
5-
This article covers an advanced topic, to understand certain edge-cases better.
4+
```warn header="Característica del lenguaje en profundidad"
5+
Este artículo cubre un tema avanzado para comprender mejor ciertos casos límite.
66
7-
It's not important. Many experienced developers live fine without knowing it. Read on if you're want to know how things work under the hood.
7+
Esto no es importante. Muchos desarrolladores experimentados viven bien sin saberlo. Sigue leyendo si quieres saber cómo funcionan las cosas por debajo de la tapa.
88
```
99

10-
A dynamically evaluated method call can lose `this`.
10+
Una llamada al método evaluado dinámicamente puede perder `this`.
1111

12-
For instance:
12+
Por ejemplo:
1313

1414
```js run
1515
let user = {
@@ -18,42 +18,42 @@ let user = {
1818
bye() { alert("Bye"); }
1919
};
2020

21-
user.hi(); // works
21+
user.hi(); // Funciona
2222

23-
// now let's call user.hi or user.bye depending on the name
23+
// Ahora llamemos a user.hi o user.bye dependiendo del nombre ingresado
2424
*!*
25-
(user.name == "John" ? user.hi : user.bye)(); // Error!
25+
(user.name == "John" ? user.hi : user.bye)(); // ¡Error!
2626
*/!*
2727
```
2828

29-
On the last line there is a conditional operator that chooses either `user.hi` or `user.bye`. In this case the result is `user.hi`.
29+
En la última linea hay un operador condicional que elije entre `user.hi` o `user.bye`. En este caso el resultado es `user.hi`.
3030

31-
Then the method is immediately called with parentheses `()`. But it doesn't work correctly!
31+
Entonces el método es llamado con paréntesis `()`. ¡Pero esto no funciona correctamente!
3232

33-
As you can see, the call results in an error, because the value of `"this"` inside the call becomes `undefined`.
33+
Como puedes ver, la llamada resulta en un error porque el valor de `"this"` dentro de la llamada se convierte en `undefined`.
3434

35-
This works (object dot method):
35+
Esto funciona (objeto, punto, método):
3636
```js
3737
user.hi();
3838
```
3939

40-
This doesn't (evaluated method):
40+
Esto no funciona (método evaluado):
4141
```js
42-
(user.name == "John" ? user.hi : user.bye)(); // Error!
42+
(user.name == "John" ? user.hi : user.bye)(); // ¡Error!
4343
```
4444

45-
Why? If we want to understand why it happens, let's get under the hood of how `obj.method()` call works.
45+
¿Por qué? Si queremos entender por qué pasa esto vayamos bajo la tapa de cómo funciona la llamada `obj.method()`.
4646

47-
## Reference type explained
47+
## Tipo de Referencia explicado
4848

49-
Looking closely, we may notice two operations in `obj.method()` statement:
49+
Mirando de cerca podemos notar dos operaciones en la declaración `obj.method()`:
5050

51-
1. First, the dot `'.'` retrieves the property `obj.method`.
52-
2. Then parentheses `()` execute it.
51+
1. Primero, el punto '.'recupera la propiedad de `obj.method`.
52+
2. Luego el paréntesis `()` lo ejecuta.
5353

54-
So, how does the information about `this` get passed from the first part to the second one?
54+
Entonces ¿cómo es trasladada la información de `this` de la primera parte a la segunda?
5555

56-
If we put these operations on separate lines, then `this` will be lost for sure:
56+
Si ponemos estas operaciones en líneas separadas, entonces `this` se perderá con seguridad:
5757

5858
```js run
5959
let user = {
@@ -62,53 +62,53 @@ let user = {
6262
}
6363

6464
*!*
65-
// split getting and calling the method in two lines
65+
// Se divide la obtención y se llama al método en dos lineas
6666
let hi = user.hi;
67-
hi(); // Error, because this is undefined
67+
hi(); // Error porque this es indefinido
6868
*/!*
6969
```
7070

71-
Here `hi = user.hi` puts the function into the variable, and then on the last line it is completely standalone, and so there's no `this`.
71+
Aquí `hi = user.hi` coloca la función dentro de una variable y luego la última linea es completamente independiente, por lo tanto no hay `this`.
7272

73-
**To make `user.hi()` calls work, JavaScript uses a trick -- the dot `'.'` returns not a function, but a value of the special [Reference Type](https://tc39.github.io/ecma262/#sec-reference-specification-type).**
73+
**Para hacer que la llamada `user.hi()` funcione, JavaScript usa un truco: el punto `'.'` no devuelve una función, sino un valor especial del [Tipo de referencia](https://tc39.github.io/ecma262/#sec-reference-specification-type).**
7474

75-
The Reference Type is a "specification type". We can't explicitly use it, but it is used internally by the language.
75+
El Tipo de Referencia es un "tipo de especificación". No podemos usarla explícitamente pero es usada internamente por el lenguaje.
7676

77-
The value of Reference Type is a three-value combination `(base, name, strict)`, where:
77+
El valor del Tipo de Referencia es una combinación de triple valor `(base, name, strict)`, donde:
7878

79-
- `base` is the object.
80-
- `name` is the property name.
81-
- `strict` is true if `use strict` is in effect.
79+
- `base` es el objeto.
80+
- `name` es el nombre de la propiedad.
81+
- `strict` es verdadero si `use strict` está en efecto.
8282

83-
The result of a property access `user.hi` is not a function, but a value of Reference Type. For `user.hi` in strict mode it is:
83+
El resultado de un acceso a la propiedad `user.hi` no es una función, sino un valor de Tipo de Referencia. Para `user.hi` en modo estricto esto es:
8484

8585
```js
86-
// Reference Type value
86+
// Valor de Tipo de Referencia
8787
(user, "hi", true)
8888
```
8989

90-
When parentheses `()` are called on the Reference Type, they receive the full information about the object and its method, and can set the right `this` (`=user` in this case).
90+
Cuando son llamados los paréntesis `()` en el tipo de referencia, reciben la información completa sobre el objeto y su método y pueden establecer el `this` correcto (`=user` en este caso).
9191

92-
Reference type is a special "intermediary" internal type, with the purpose to pass information from dot `.` to calling parentheses `()`.
92+
Tipo de Referencia es un tipo interno de "intermediario", con el propósito de pasar información desde el punto `.` hacia los paréntesis de la llamada `()`.
9393

94-
Any other operation like assignment `hi = user.hi` discards the reference type as a whole, takes the value of `user.hi` (a function) and passes it on. So any further operation "loses" `this`.
94+
Cualquier otra operación como la asignación `hi = user.hi` descarta el tipo de referencia como un todo, toma el valor de `user.hi` (una función) y lo pasa. Entonces cualquier operación "pierde" `this`.
9595

96-
So, as the result, the value of `this` is only passed the right way if the function is called directly using a dot `obj.method()` or square brackets `obj['method']()` syntax (they do the same here). Later in this tutorial, we will learn various ways to solve this problem such as [func.bind()](/bind#solution-2-bind).
96+
Entonces, como resultado, el valor de `this` solo se pasa de la manera correcta si la función se llama directamente usando una sintaxis de punto `obj.method()` o corchetes `obj['method']()` (aquí hacen lo mismo). Más adelante en este tutorial, aprenderemos varias formas de resolver este problema así como [func.bind()](/bind#solution-2-bind).
9797

98-
## Summary
98+
## Resumen
9999

100-
Reference Type is an internal type of the language.
100+
El Tipo de Referencia es un tipo interno del lenguaje.
101101

102-
Reading a property, such as with dot `.` in `obj.method()` returns not exactly the property value, but a special "reference type" value that stores both the property value and the object it was taken from.
102+
Leer una propiedad como las que tienen un punto `.` en `obj.method()` no devuelve exactamente el valor de la propiedad, sino un valor especial de "tipo de referencia" que almacena tanto el valor de la propiedad como el objeto del que se tomó.
103103

104-
That's for the subsequent method call `()` to get the object and set `this` to it.
104+
Eso se hace para la llamada `()` al siguiente método para obtener el objeto y establecer `this` en él.
105105

106-
For all other operations, the reference type automatically becomes the property value (a function in our case).
106+
Para todas las demás operaciones, el tipo de referencia se convierte automáticamente en el valor de la propiedad (una función en nuestro caso).
107107

108-
The whole mechanics is hidden from our eyes. It only matters in subtle cases, such as when a method is obtained dynamically from the object, using an expression.
108+
Toda la mecánica está oculta a nuestros ojos. Solo importa en casos sutiles, como cuando un método se obtiene dinámicamente del objeto, usando una expresión.
109109

110110

111111

112112

113113

114-
result of dot `.` isn't actually a method, but a value of `` needs a way to pass the information about `obj`
114+
El resultado del punto `.` no es en realidad un método, pero un valor de `` necesita una manera de pasar la información sobre `obj`.

1-js/99-js-misc/index.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,2 @@
1-
21
# Temas diversos
2+

0 commit comments

Comments
 (0)