You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
By specification, object property keys may be either of string type, or of symbol type. Not numbers, not booleans, only strings or symbols, these two types.
4
+
Por especificación, las claves (Keys) de un objeto deben ser solamente del tipo String o Symbol. Solamente esos dos: String o Symbol.
5
5
6
-
Till now we've been using only strings. Now let's see the benefits that symbols can give us.
6
+
Hasta ahora sólo hemos aprendido acerca de los Strings, por lo que es momento de conocer las ventajas que Symbol nos puede dar.
7
7
8
8
## Symbols
9
9
10
-
A "symbol" represents a unique identifier.
10
+
El valor de "Symbol" representa un identificador único.
11
11
12
-
A value of this type can be created using`Symbol()`:
12
+
Un valor de este tipo puede ser creado usando`Symbol()`:
13
13
14
14
```js
15
-
// id is a new symbol
15
+
// id es un nuevo symbol
16
16
let id =Symbol();
17
17
```
18
18
19
-
Upon creation, we can give symbol a description (also called a symbol name), mostly useful for debugging purposes:
19
+
También le podemos agregar una descripción (también llamada symbol name), que será útil en la depuración de código:
20
20
21
-
```js
22
-
// id is a symbol with the description "id"
21
+
```js run
22
+
// id es un symbol con la descripción "id"
23
23
let id =Symbol("id");
24
24
```
25
25
26
-
Symbols are guaranteed to be unique. Even if we create many symbols with the same description, they are different values. The description is just a label that doesn't affect anything.
26
+
Se garantiza que los símbolos son únicos. Aunque declaremos varios Symbols con la misma descripción, éstos tendrán valores distintos. La descripción es solamente una etiqueta que no afecta nada más.
27
27
28
-
For instance, here are two symbols with the same description -- they are not equal:
28
+
Por ejemplo, aquí hay dos Symbols con la misma descripción -- pero no son iguales:
29
29
30
30
```js run
31
31
let id1 =Symbol("id");
@@ -36,31 +36,31 @@ alert(id1 == id2); // false
36
36
*/!*
37
37
```
38
38
39
-
If you are familiar with Ruby or another language that also has some sort of "symbols" -- please don't be misguided. JavaScript symbols are different.
39
+
Si estás familiarizado con Ruby u otro lenguaje que también tiene symbols -- por favor no te confundas. Los Symbols de Javascript son diferentes.
40
40
41
-
````warn header="Symbols don't auto-convert to a string"
42
-
Most values in JavaScript support implicit conversion to a string. For instance, we can `alert` almost any value, and it will work. Symbols are special. They don't auto-convert.
41
+
````warn header="Symbols no se autoconvierten a String"
42
+
La mayoría de los valores en JavaScript soportan la conversión implícita a string. Por ejemplo, podemos hacer un ´alert´ con casi cualquier valor y funcionará. Los Symbols son distintos, éstos no se auto-convierten.
43
43
44
-
For instance, this `alert` will show an error:
44
+
Por ejemplo, este `alert` mostrará un error:
45
45
46
46
```js run
47
47
let id = Symbol("id");
48
48
*!*
49
-
alert(id); // TypeError: Cannot convert a Symbol value to a string
49
+
alert(id); // TypeError: No puedes convertir un valor Symbol en string
50
50
*/!*
51
51
```
52
52
53
-
That's a "language guard" against messing up, because strings and symbols are fundamentally different and should not accidentally convert one into another.
53
+
Esa es una "protección del lenguaje" para evitar errores ya que los String y los Symbol son diferentes y no deberían convertirse ocasionalmente uno en otro.
54
54
55
-
If we really want to show a symbol, we need to explicitly call `.toString()` on it, like here:
55
+
Si realmente queremos mostrar un Symbol, necesitamos llamar el método `.toString()` de la siguiente manera:
56
56
```js run
57
57
let id = Symbol("id");
58
58
*!*
59
-
alert(id.toString()); // Symbol(id), now it works
59
+
alert(id.toString()); // Symbol(id), ahora sí funciona
60
60
*/!*
61
61
```
62
62
63
-
Or get `symbol.description` property to show the description only:
63
+
O se puede utilizar `symbol.description` para obtener la descripción solamente:
64
64
```js run
65
65
let id = Symbol("id");
66
66
*!*
@@ -70,80 +70,78 @@ alert(id.description); // id
70
70
71
71
````
72
72
73
-
## "Hidden" properties
73
+
## Claves "Ocultas"
74
74
75
-
Symbols allow us to create "hidden" properties of an object, that no other part of code can accidentally access or overwrite.
75
+
Los Symbols nos permiten crear claves "ocultas" en un objeto, a las cuales ninguna otra parte del código puede accesar ni sobrescribir.
76
76
77
-
For instance, if we're working with `user` objects, that belong to a third-party code. We'd like to add identifiers to them.
78
-
79
-
Let's use a symbol key for it:
77
+
Por ejemplo, si queremos guardar un "identificador" para el objeto `user`, podemos asignar un symbol como clave del objeto:
80
78
81
79
```js run
82
-
let user = { //belongs to another code
80
+
let user = { //pertenece a otro código
83
81
name:"John"
84
82
};
85
83
86
84
let id =Symbol("id");
87
85
88
86
user[id] =1;
89
87
90
-
alert( user[id] ); //we can access the data using the symbol as the key
88
+
alert( user[id] ); //podemos accesar a la información utilizando el symbol como nombre de clave
91
89
```
92
90
93
-
What's the benefit of using `Symbol("id")`over a string `"id"`?
91
+
¿Cuál es la ventaja de usar `Symbol("id")`y no un string `"id"`?
94
92
95
-
As `user` objects belongs to another code, and that code also works with them, we shouldn't just add any fields to it. That's unsafe. But a symbol cannot be accessed accidentally, the third-party code probably won't even see it, so it's probably all right to do.
93
+
Vamos a profundizar en el ejemplo para que sea más claro.
96
94
97
-
Also, imagine that another script wants to have its own identifier inside`user`, for its own purposes. That may be another JavaScript library, so that the scripts are completely unaware of each other.
95
+
Imagina que otro script quiere tener la clave "id" dentro de`user` para sus propios fines. Puede ser otra librería de JavaScript, por lo cual ninguno de los scripts saben de su coexistencia.
98
96
99
-
Then that script can create its own`Symbol("id")`, like this:
97
+
Y entonces ese script puede crear su propio`Symbol("id")`, como este:
100
98
101
99
```js
102
100
// ...
103
101
let id =Symbol("id");
104
102
105
-
user[id] ="Their id value";
103
+
user[id] ="Su id";
106
104
```
107
105
108
-
There will be no conflict between our and their identifiers, because symbols are always different, even if they have the same name.
106
+
No habrá conflicto porque los Symbols siempre son diferentes, incluso si tienen el mismo nombre.
109
107
110
-
...But if we used a string `"id"`instead of a symbol for the same purpose, then there *would* be a conflict:
108
+
Ahora ten en cuenta que si utilizamos un string `"id"`en lugar de un Symbol para el mismo propósito, entonces SÍ *habría* un conflicto:
111
109
112
110
```js run
113
111
let user = { name:"John" };
114
112
115
-
//Our script uses "id" property
116
-
user.id="Our id value";
113
+
//Nuestro script usa la clave "id"
114
+
user.id="Nuestro valor id";
117
115
118
-
// ...Another script also wants "id" for its purposes...
116
+
// ...Otro script también quiere usar "id" ...
119
117
120
-
user.id="Their id value"
121
-
// Boom! overwritten by another script!
118
+
user.id="Su valor de id"
119
+
// Boom! sobreescrito para otro script!
122
120
```
123
121
124
-
### Symbols in a literal
122
+
### Symbols en objetos literales
125
123
126
-
If we want to use a symbol in an object literal`{...}`, we need square brackets around it.
124
+
Si queremos usar un Symbol en un objeto literal, debemos usar llaves.
127
125
128
-
Like this:
126
+
Como se muestra a continuación:
129
127
130
128
```js
131
129
let id =Symbol("id");
132
130
133
131
let user = {
134
132
name:"John",
135
133
*!*
136
-
[id]:123//not "id: 123"
134
+
[id]:123//no "id: 123"
137
135
*/!*
138
136
};
139
137
```
140
-
That's because we need the value from the variable `id`as the key, not the string "id".
138
+
Se hace así porque necesitamos que el valor de la variable `id`sea la clave, no el string "id".
141
139
142
-
### Symbols are skipped by for..in
140
+
### Los Symbols son omitidos en for..in
143
141
144
-
Symbolic properties do not participate in `for..in` loop.
142
+
Las claves de Symbol no participan dentro de los ciclos `for..in`.
145
143
146
-
For instance:
144
+
Por ejemplo:
147
145
148
146
```js run
149
147
let id =Symbol("id");
@@ -154,16 +152,16 @@ let user = {
154
152
};
155
153
156
154
*!*
157
-
for (let key in user) alert(key); //name, age (no symbols)
155
+
for (let key in user) alert(key); //nombre, edad (no symbols)
158
156
*/!*
159
157
160
-
//the direct access by the symbol works
158
+
//el acceso directo a la clave de symbol funciona
161
159
alert( "Direct: "+ user[id] );
162
160
```
163
161
164
-
`Object.keys(user)` also ignores them. That's a part of the general "hiding symbolic properties" principle. If another script or a library loops over our object, it won't unexpectedly access a symbolic property.
162
+
Esto forma parte del concepto general de "ocultamiento". Si otro script o si otra librería itera el objeto este no accesará a la clave de Symbol.
165
163
166
-
In contrast, [Object.assign](mdn:js/Object/assign)copies both string and symbol properties:
164
+
En contraste, [Object.assign](mdn:js/Object/assign)copia las claves tanto del string como las del symbol:
167
165
168
166
```js run
169
167
let id =Symbol("id");
@@ -176,102 +174,104 @@ let clone = Object.assign({}, user);
176
174
alert( clone[id] ); // 123
177
175
```
178
176
179
-
There's no paradox here. That's by design. The idea is that when we clone an object or merge objects, we usually want *all* properties to be copied (including symbols like `id`).
177
+
No hay paradoja aquí, es así por diseño. La idea es que cuando clonamos un objeto o cuando fusionamos objetos, generalmente queremos que se copien *todas* las claves (incluidos los Symbol como `id`).
178
+
179
+
## Symbols Globales
180
180
181
-
## Global symbols
181
+
Como hemos visto, normalmente todos los Symbols son diferentes aunque tengan el mismo nombre. Pero algunas veces necesitamos que los symbol con el mismo nombre sean las mismas entidades.
182
182
183
-
As we've seen, usually all symbols are different, even if they have the same name. But sometimes we want same-named symbols to be same entities. For instance, different parts of our application want to access symbol `"id"`meaning exactly the same property.
183
+
Por ejemplo, distintas partes de nuestra aplicación quieren accesar a symbol `"id"`queriendo obtener el mismo valor de la clave.
184
184
185
-
To achieve that, there exists a *global symbol registry*. We can create symbols in it and access them later, and it guarantees that repeated accesses by the same name return exactly the same symbol.
185
+
Para lograr esto, existe un *global symbol registry*. Ahí podemos crear symbols y acceder después a ellos, lo cual nos garantiza que cada vez que se acceda a la clave con el mismo nombre, esta te devuelva exactamente el mismo symbol.
186
186
187
-
In order to read (create if absent) a symbol from the registry, use`Symbol.for(key)`.
187
+
Para crear u accesar a un symbol en el registro global, usa`Symbol.for(key)`.
188
188
189
-
That call checks the global registry, and if there's a symbol described as`key`, then returns it, otherwise creates a new symbol `Symbol(key)`and stores it in the registry by the given`key`.
189
+
Esta llamada revisa el registro global, y si existe un symbol descrito como`key`, lo retornará, de lo contrario creará un nuevo symbol `Symbol(key)`y lo almacenará en el registro por su`key`.
190
190
191
-
For instance:
191
+
Por ejemplo:
192
192
193
193
```js run
194
-
//read from the global registry
195
-
let id =Symbol.for("id"); //if the symbol did not exist, it is created
194
+
//leer desde el registro global
195
+
let id =Symbol.for("id"); //si el símbolo no existe, se crea
196
196
197
-
//read it again (maybe from another part of the code)
197
+
//léelo nuevamente (tal vez de otra parte del código)
198
198
let idAgain =Symbol.for("id");
199
199
200
-
//the same symbol
200
+
//el mismo symbol
201
201
alert( id === idAgain ); // true
202
202
```
203
203
204
-
Symbols inside the registry are called *global symbols*. If we want an application-wide symbol, accessible everywhere in the code -- that's what they are for.
204
+
Los Symbols dentro de este registro son llamados *global symbols* y están disponibles y al alcance de todo el código en la aplicación.
205
205
206
-
```smart header="That sounds like Ruby"
207
-
In some programming languages, like Ruby, there's a single symbol per name.
206
+
```smart header="Eso suena a Ruby"
207
+
En algunos lenguajes de programación como Ruby, hay un solo Symbol por cada nombre.
208
208
209
-
In JavaScript, as we can see, that's right for global symbols.
209
+
En Javascript, como podemos ver, existen los global symbols.
210
210
```
211
211
212
212
### Symbol.keyFor
213
213
214
-
For global symbols, not only`Symbol.for(key)`returns a symbol by name, but there's a reverse call: `Symbol.keyFor(sym)`, that does the reverse: returns a name by a global symbol.
214
+
Para los global symbols, no solo`Symbol.for(key)`devuelve un symbol por su nombre, sino que existe una llamada inversa: `Symbol.keyFor(sym)` que hace lo contrario: devuelve el nombre de un global symbol.
215
215
216
-
For instance:
216
+
Por ejemplo:
217
217
218
218
```js run
219
-
//get symbol by name
220
-
let sym =Symbol.for("name");
219
+
//tomar symbol por nombre
220
+
let sym =Symbol.for("nombre");
221
221
let sym2 =Symbol.for("id");
222
222
223
-
//get name by symbol
224
-
alert( Symbol.keyFor(sym) ); //name
223
+
//tomar name por symbol
224
+
alert( Symbol.keyFor(sym) ); //nombre
225
225
alert( Symbol.keyFor(sym2) ); // id
226
226
```
227
227
228
-
The`Symbol.keyFor`internally uses the global symbol registry to look up the key for the symbol. So it doesn't work for non-global symbols. If the symbol is not global, it won't be able to find it and returns`undefined`.
228
+
El`Symbol.keyFor`utiliza internamente el registro "global symbol registry" para buscar la clave del symbol, por lo tanto, no funciona para los symbol que no están dentro del registro. Si el symbol no es global, no será capaz de encontrarlo y por lo tanto devolverá`undefined`.
229
229
230
-
That said, any symbols have`description`property.
230
+
Dicho esto, todo symbol tiene`description`de clave.
231
231
232
-
For instance:
232
+
Por ejemplo:
233
233
234
234
```js run
235
-
let globalSymbol =Symbol.for("name");
236
-
let localSymbol =Symbol("name");
235
+
let globalSymbol =Symbol.for("nombre");
236
+
let localSymbol =Symbol("nombre");
237
237
238
-
alert( Symbol.keyFor(globalSymbol) ); //name, global symbol
239
-
alert( Symbol.keyFor(localSymbol) ); // undefined, not global
238
+
alert( Symbol.keyFor(globalSymbol) ); //nombre, global symbol
239
+
alert( Symbol.keyFor(localSymbol) ); // undefined, no global
240
240
241
-
alert( localSymbol.description ); //name
241
+
alert( localSymbol.description ); //nombre
242
242
```
243
243
244
244
## System symbols
245
245
246
-
There exist many "system" symbols that JavaScript uses internally, and we can use them to fine-tune various aspects of our objects.
246
+
Existen varios symbols del sistema que JavaScript utiliza internamente, y que podemos usar para ajustar varios aspectos de nuestros objetos.
247
247
248
-
They are listed in the specification in the [Well-known symbols](https://tc39.github.io/ecma262/#sec-well-known-symbols)table:
248
+
Se encuentran listados en [Well-known symbols](https://tc39.github.io/ecma262/#sec-well-known-symbols) :
249
249
250
250
-`Symbol.hasInstance`
251
251
-`Symbol.isConcatSpreadable`
252
252
-`Symbol.iterator`
253
253
-`Symbol.toPrimitive`
254
-
- ...and so on.
254
+
- ...y así.
255
255
256
-
For instance, `Symbol.toPrimitive`allows us to describe object to primitive conversion. We'll see its use very soon.
256
+
Por ejemplo, `Symbol.toPrimitive`nos permite describir el objeto para su conversión primitiva. Más adelante veremos su uso.
257
257
258
-
Other symbols will also become familiar when we study the corresponding language features.
258
+
Otros symbols también te serán más familiares cuando estudiemos las características correspondientes.
259
259
260
-
## Summary
260
+
## Resumen
261
261
262
-
`Symbol`is a primitive type for unique identifiers.
262
+
`Symbol`es un tipo de dato primitivo para identificadores únicos.
263
263
264
-
Symbols are created with `Symbol()`call with an optional description (name).
264
+
Symbols son creados al llamar `Symbol()`con una descripción opcional.
265
265
266
-
Symbols are always different values, even if they have the same name. If we want same-named symbols to be equal, then we should use the global registry: `Symbol.for(key)`returns (creates if needed) a global symbol with `key`as the name. Multiple calls of`Symbol.for`with the same `key` return exactly the same symbol.
266
+
Symbols son siempre valores distintos aunque tengan el mismo nombre. Si queremos que symbols con el mismo nombre tengan el mismo valor, entonces debemos guardarlos en el registro global: `Symbol.for(key)`retornará un symbol (en caso de no existir, lo creará) con el `key`como su nombre. Múltiples llamadas de`Symbol.for`retornarán siempre el mismo symbol.
267
267
268
-
Symbols have two main use cases:
268
+
Symbols se utilizan principalmente en dos casos:
269
269
270
-
1."Hidden" object properties.
271
-
If we want to add a property into an object that "belongs" to another script or a library, we can create a symbol and use it as a property key. A symbolic property does not appear in `for..in`, so it won't be accidentally processed together with other properties. Also it won't be accessed directly, because another script does not have our symbol. So the property will be protected from accidental use or overwrite.
270
+
1.Claves(keys) "Ocultas" dentro de un objeto.
271
+
Si queremos agregar una clave a un objeto que "pertenezca" a otro script u otra librería, podemos crear un symbol y usarlo como clave. Una clave de symbol no aparecerá en los ciclos `for..in`,por lo que no aparecerá listada. Tampoco podrá ser accesada directamente por otro script porque este no tendrá nuestro symbol y no podrá intervenir en sus acciones.
272
272
273
-
So we can "covertly" hide something into objects that we need, but others should not see, using symbolic properties.
273
+
Podemos "ocultar" ciertos valores dentro de un objeto que solo estarán disponibles dentro de ese script usando las claves de symbol.
274
274
275
-
2.There are many system symbols used by JavaScript which are accessible as `Symbol.*`. We can use them to alter some built-in behaviors. For instance, later in the tutorial we'll use `Symbol.iterator`for[iterables](info:iterable), `Symbol.toPrimitive`to setup[object-to-primitive conversion](info:object-toprimitive) and so on.
275
+
2.Existen diversos symbols del sistema que utiliza Javascript, a los cuales podemos accesar por medio de `Symbol.*`. Podemos usarlos para alterar algunos comportamientos. Por ejemplo, más adelante en el tutorial, usaremos `Symbol.iterator`para[iterables](info:iterable), `Symbol.toPrimitive`para configurar[object-to-primitive conversion](info:object-toprimitive).
276
276
277
-
Technically, symbols are not 100% hidden. There is a built-in method [Object.getOwnPropertySymbols(obj)](mdn:js/Object/getOwnPropertySymbols)that allows us to get all symbols. Also there is a method named [Reflect.ownKeys(obj)](mdn:js/Reflect/ownKeys)that returns *all* keys of an object including symbolic ones. So they are not really hidden. But most libraries, built-in functions and syntax constructs don't use these methods.
277
+
Técnicamente, los symbols no están 100% ocultos. Existe un método incorporado [Object.getOwnPropertySymbols(obj)](mdn:js/Object/getOwnPropertySymbols)que nos permite obtener todos los symbols. También existe un método llamado [Reflect.ownKeys(obj)](mdn:js/Reflect/ownKeys)que devuelve *todas* las claves de un objeto, incluyendo las que son de tipo symbol. Por lo tanto, no están realmente ocultos, aunque la mayoría de las librerías, los métodos incorporados y las construcciones de sintaxis se adhieren a un acuerdo común de que sí lo están. Y el que explícitamente llama a los métodos antes mencionados probablemente entiende bien lo que está haciendo.
0 commit comments