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

Symbol type#115

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

Closed
mariabp wants to merge11 commits intojavascript-tutorial:masterfrommariabp:spanish-symbol
Closed
Changes fromall commits
Commits
Show all changes
11 commits
Select commitHold shift + click to select a range
6f952dc
First translation
mariabpOct 22, 2019
de0b438
Update article.md
mariabpNov 1, 2019
0a786f0
Deleted extra space between declaration and name of variable
Nov 8, 2019
239004b
Update 1-js/04-object-basics/03-symbol/article.md
vplentinaxJun 10, 2020
969795a
Update 1-js/04-object-basics/03-symbol/article.md
vplentinaxJun 10, 2020
82a0bb0
Update 1-js/04-object-basics/03-symbol/article.md
vplentinaxJun 10, 2020
68d693c
Update 1-js/04-object-basics/03-symbol/article.md
vplentinaxJun 10, 2020
505e32b
Update 1-js/04-object-basics/03-symbol/article.md
vplentinaxJun 10, 2020
5015fc3
Update 1-js/04-object-basics/03-symbol/article.md
vplentinaxJun 10, 2020
6ba4d07
Update 1-js/04-object-basics/03-symbol/article.md
vplentinaxJun 10, 2020
63349ea
Update 1-js/04-object-basics/03-symbol/article.md
vplentinaxJun 10, 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
208 changes: 104 additions & 104 deletions1-js/04-object-basics/03-symbol/article.md
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,31 @@

#Symbol type
#Tipo Symbol

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.
Por especificación, las "propiedades claves" (key) de un objeto deben ser solamente del tipo String o Symbol. No Number, no Boolean, solo esos dos: string o symbol.

Till now we've only seen strings. Now let's see the advantages that symbols can give us.
Hasta ahora sólo hemos aprendido acerca de los Strings, por lo que es momento de conocer las ventajas que Symbol nos puede dar.

## Symbols

"Symbol"value represents a unique identifier.
El valor de"Symbol"representa un identificador único.

A value of this type can be created using `Symbol()`:
Un valor de este tipo puede ser creado usando `Symbol()`:

```js
// idis a new symbol
// ides un nuevo symbol
let id = Symbol();
```

We can also give symbol a description (also called asymbol name),mostly useful for debugging purposes:
También le podemos agregar una descripción (también llamadasymbol name),que será útil en la depuración de código:

```js run
// idis a symbolwith the description "id"
// ides un symbolcon la descripción "id"
let id = Symbol("id");
```

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

For instance, here are two symbols with the same description --they are not equal:
Por ejemplo, aquí hay dos Symbols con la misma descripción --pero no son iguales:

```js run
let id1 = Symbol("id");
Expand All@@ -36,12 +36,12 @@ alert(id1 == id2); // false
*/!*
```

If you are familiar withRubyor another language that also has some sort of "symbols" --please don't be misguided. JavaScript symbols are different.
Si estás familiarizado conRubyu otro lenguaje que también tienesymbols --por favor no te confundas. Los Symbols de Javascript son diferentes.

````warn header="Symbolsdon't auto-convert to astring"
Most values inJavaScriptsupport implicit conversion to a string.For instance, we can `alert` almost any value, and it will work.Symbolsare special. They don'tauto-convert.
````warn header="Symbolsno se autoconvierten aString"
La mayoría de los valores enJavaScriptsoportan la conversión implícita a string.Por ejemplo, podemos hacer un ´alert´ con casi cualquier valor y funcionará. LosSymbolsson distintos, éstos no seauto-convierten.

For instance, this `alert`will show an error:
Por ejemplo, este `alert`mostrará un error:

```js run
let id = Symbol("id");
Expand All@@ -50,17 +50,17 @@ alert(id); // TypeError: Cannot convert a Symbol value to a string
*/!*
```

That's a "language guard" against messing up, because strings and symbols are fundamentally different and should not occasionally convert one into another.
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.

If we really want to show a symbol, we need to call `.toString()`on it, like here:
Si realmente queremos mostrar un Symbol, necesitamos llamar el método `.toString()`de la siguiente manera:
```js run
let id = Symbol("id");
*!*
alert(id.toString()); // Symbol(id),now it works
alert(id.toString()); // Symbol(id),ahora sí funciona
*/!*
```

Or get`symbol.description`property to get the description only:
O se puede utilizar`symbol.description`para obtener la descripción solamente:
```js run
let id = Symbol("id");
*!*
Expand All@@ -70,213 +70,213 @@ alert(id.description); // id

````

##"Hidden" properties
##Propiedades "Ocultas"

Symbolsallow us to create "hidden" properties of an object, that no other part of code can occasionally access or overwrite.
LosSymbolsnos permiten crear propiedades "ocultas" en un objeto, a las cuales ninguna otra parte del código puede accesar ni sobrescribir.

For instance, if we want to store an "identifier" for the object `user`,we can use asymbolas a key for it:
Por ejemplo, si queremos guardar un "identificador" para el objeto `usuario`,podemos asignar unsymbolcomo propiedad del objeto:

```js run
letuser = {name: "John" };
letusuario = {nombre: "Juan" };
let id = Symbol("id");

user[id] = "ID Value";
alert(user[id] ); //we can access the data using thesymbolas the key
usuario[id] = "ID Value";
alert(usuario[id] ); //podemos accesar a la información utilizandosymbolcomo propiedad
```

What's the benefit of using`Symbol("id")`over a string `"id"`?
¿Cuál es la ventaja de usar`Symbol("id")`y no un string `"id"`?

Let's make the example a bit deeper to see that.
Vamos a profundizar en el ejemplo para que sea más claro.

Imagine that another scriptwants to have its own"id"property inside `user`, for its own purposes. That may be another JavaScript library, so the scripts are completely unaware of each other.
Imagina que otro scriptquiere tener la propiedad"id"dentro de `usuario` para sus propios fines. Puede ser otra librería de JavaScript, por lo cual ninguno de los scripts saben de su coexistencia.

Then thatscriptcan create its own `Symbol("id")`,like this:
Y entonces esescriptpuede crear su propio `Symbol("id")`,como este:

```js
// ...
let id = Symbol("id");

user[id] = "Their id value";
usuario[id] = "Valor de id";
```

There will be no conflict, because symbols are always different, even if they have the same name.
No habrá conflicto porque los Symbols siempre son diferentes, incluso si tienen el mismo nombre.

Now note that if we used astring `"id"`instead of a symbol for the same purpose, then there *would* be a conflict:
Ahora ten en cuenta que si utilizamos unstring `"id"`en lugar de un Symbol para el mismo propósito, entonces SÍ *habría* un conflicto:

```js run
letuser = {name: "John" };
letusuario = {nombre: "Juan" };

//our scriptuses"id" property
user.id = "ID Value";
//nuestro scriptusa la propiedad"id"
usuario.id = "ID Value";

// ...if later another scriptthe uses"id"for its purposes...
// ...si luego otro scriptusa"id"para sus propósitos...

user.id = "Their id value"
//boom! overwritten! it did not mean to harm the colleague, but did it!
usuario.id = "Valor de id"
//¡Boom, queda sobreescrito!
```

### Symbolsin a literal
### Symbolsen objetos literales

If we want to use a symbol in an objectliteral,we need square brackets.
Si queremos usar un Symbol en un objetoliteral,debemos usar llaves.

Like this:
Como se muestra a continuación:

```js
let id = Symbol("id");

let user = {
name: "John",
nombre: "Juan",
*!*
[id]: 123 //not just "id: 123"
[id]: 123 //no solo "id: 123"
*/!*
};
```
That's because we need the value from thevariable `id`as the key, not the string "id".
Se hace así porque necesitamos que el valor de lavariable `id`sea la propiedad, no el string "id".

### Symbolsare skipped by for..in
###LosSymbolsson omitidos en for..in

Symbolic properties do not participate in`for..in` loop.
Las propiedades de Symbol no participan dentro de los ciclos`for..in`.

For instance:
Por ejemplo:

```js run
let id = Symbol("id");
letuser = {
name: "John",
age: 30,
[id]: 123
letusuario = {
nombre: "Juan",
edad: 30,
[id]: 123
};

*!*
for (let key inuser) alert(key); //name, age (no symbols)
for (letkeyin usuario) alert(key); //nombre, edad (no symbols)
*/!*

//the direct access by thesymbolworks
//el acceso directo a la propiedad desymbolfunciona
alert( "Direct: " + user[id] );
```

That's a part of the general"hiding" concept. If another scriptor a library loops over our object, it won't unexpectedly access a symbolic property.
Esto forma parte del concepto generalde "ocultamiento". Si otro scripto si otra librería itera el objeto este no accesará a la propiedad de Symbol.

In contrast, [Object.assign](mdn:js/Object/assign)copies bothstringand symbol properties:
En contraste, [Object.assign](mdn:js/Object/assign)copia las propiedades tanto delstringcomo las del symbol:

```js run
let id = Symbol("id");
letuser = {
[id]: 123
letusuario = {
[id]: 123
};

let clone = Object.assign({},user);
let clone = Object.assign({},usuario);

alert( clone[id] ); // 123
```

There's no paradox here. That's by design. The ideais that when we clone an object or merge objects, we usually want *all* properties to be copied (including symbols like `id`).
No hay paradoja aquí, es así por diseño. La ideaes que cuando clonamos un objeto o cuando fusionamos objetos, generalmente queremos que se copien *todas* las propiedades (incluidos los Symbol como `id`).

````smart header="Property keys of other types are coerced to strings"
We can only usestringsor symbolsas keys in objects. Other types are converted to strings.
Podemos usar solamentestringso symbolscomo propiedades de los objetos. Otros tipos de datos son convertidos a string.

For instance, a number `0`becomes astring `"0"` when used as a property key:
Por ejemplo, el número `0`se convierte alstring `'0'` cuando es usado como propiedad de un objeto:

```js run
let obj = {
0: "test" //same as "0": "test"
0: "test" //igual que "0": "test"
};

//bothalertsaccess the same property (the number 0is converted to string "0")
//los dosalertspueden accesar a la misma propiedad (el número 0es convertido a string "0")
alert( obj["0"] ); // test
alert( obj[0] ); // test (same property)
alert( obj[0] ); // test (misma propiedad)
```
````

##Global symbols
##Symbols Globales

As we've seen, usually all symbols are different, even if they have the same names. But sometimes we want same-named symbols to be same entities.
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.

For instance, different parts of our application want to access symbol `"id"`meaning exactly the same property.
Por ejemplo, distintas partes de nuestra aplicación quieren accesar a symbol `"id"`queriendo obtener el mismo valor de la propiedad.

To achieve that, there exists a*global symbol registry*.We can create symbolsin it and access them later, and it guarantees that repeated accesses by the same name return exactly the same symbol.
Para lograr esto, existe un*global symbol registry*.Ahí podemos crear symbolsy acceder después a ellos, lo cual nos garantiza que cada vez que se acceda a la propiedad con el mismo nombre, esta te devuelva exactamente el mismo symbol.

In order to create or read asymbolin the registry, use `Symbol.for(key)`.
Para crear u accesar a unsymbolen el registro global, usa `Symbol.for(key)`.

That call checks the global registry, and if there's a symboldescribed as `key`,then returns it, otherwise creates a newsymbol `Symbol(key)`and stores it in the registry by the given `key`.
Esta llamada revisa el registro global, y si existe un symboldescrito como `key`,lo retornará, de lo contrario creará un nuevosymbol `Symbol(key)`y lo almacenará en el registro por su `key`.

For instance:
Por ejemplo:

```js run
//read from the global registry
let id = Symbol.for("id"); //if thesymboldid not exist, it is created
//accesar al registro global
let id = Symbol.for("id"); //sisymbolno existe, será creado

//read it again
letidAgain = Symbol.for("id");
//accesar una vez más
letidOtraVez = Symbol.for("id");

//the same symbol
alert(id ===idAgain); // true
//el mismo symbol
alert(id ===idOtraVez); // true
```

Symbolsinside the registry are called*global symbols*. If we want an application-wide symbol, accessible everywhere in the code -- that's what they are for.
LosSymbolsdentro de este registro son llamados*global symbols* y están disponibles y al alcance de todo el código en la aplicación.

```smart header="That sounds like Ruby"
In some programming languages, likeRuby,there's a single symbol per name.
```smart header="Eso suena a Ruby"
En algunos lenguajes de programación comoRuby,hay un solo Symbol por cada nombre.

In JavaScript, as we can see, that's right for global symbols.
En Javascript, como podemos ver, existen los global symbols.
```

### Symbol.keyFor

Forglobal symbols,not only `Symbol.for(key)`returns a symbolby name, but there's a reverse call: `Symbol.keyFor(sym)`,that does the reverse: returns a name by a global symbol.
Para losglobal symbols,no solo `Symbol.for(key)`retorna un symbolpor su nombre, si no que existe una llamada inversa: `Symbol.keyFor(sym)`,que hace lo contrario: retorna el nombre de un global symbol.

For instance:
Por ejemplo:

```js run
let sym = Symbol.for("name");
let sym = Symbol.for("nombre");
let sym2 = Symbol.for("id");

//get name from symbol
alert( Symbol.keyFor(sym) ); //name
//obtener nombre de un symbol
alert( Symbol.keyFor(sym) ); //nombre
alert( Symbol.keyFor(sym2) ); // id
```

The `Symbol.keyFor`internally uses the global symbol registryto look up the key for the symbol. So it doesn't work for non-global symbols. If the symbolis not global,it won't be able to find it and return `undefined`.
El `Symbol.keyFor`utiliza internamente el global symbol registrypara buscar la propiedad del symbol, por lo tanto, no funciona para los symbol que no están dentro del registro. Si el symbolno es global,no será capaz de encontrarlo y por lo tanto retornará `undefined`.

For instance:
Por ejemplo:

```js run
alert( Symbol.keyFor(Symbol.for("name")) ); //name, global symbol
alert( Symbol.keyFor(Symbol.for("nombre")) ); //nombre, global symbol

alert( Symbol.keyFor(Symbol("name2")) ); // undefined,the argument isn't a global symbol
alert( Symbol.keyFor(Symbol("nombre2")) ); // undefined,el argumento no es un global symbol
```

## System symbols

There exist many "system" symbols that JavaScriptuses internally, and we can use them to fine-tune various aspects of our objects.
Existen varios symbols del sistema que JavaScriptutiliza internamente, y que podemos usar para ajustar varios aspectos de nuestros objetos.

They are listed in the specification in the[Well-known symbols](https://tc39.github.io/ecma262/#sec-well-known-symbols)table:
Se encuentran listados en[Well-known symbols](https://tc39.github.io/ecma262/#sec-well-known-symbols) :

- `Symbol.hasInstance`
- `Symbol.isConcatSpreadable`
- `Symbol.iterator`
- `Symbol.toPrimitive`
- ...and so on.
- ...y así.

For instance, `Symbol.toPrimitive`allows us to describe object to primitive conversion. We'll see its use very soon.
Por ejemplo, `Symbol.toPrimitive`nos permite describir el objeto para su conversión primitiva. Más adelante veremos su uso.

Other symbolswill also become familiar when we study the corresponding language features.
Otros symbolstambién te serán más familiares cuando estudiemos las características correspondientes.

##Summary
##Resumen

`Symbol`is a primitive type for unique identifiers.
`Symbol`es un tipo de dato primitivo para identificadores únicos.

Symbolsare created with`Symbol()`call with an optional description.
Symbolsson creados al llamar`Symbol()`con una descripción opcional.

Symbolsare 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`return exactly the same symbol.
Symbolsson 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.

Symbolshave two main use cases:
Symbolsse utilizan principalmente en dos casos:

1."Hidden" object properties.
If we want to add a property into an object that "belongs" to another scriptor a library, we can create asymboland use it as a property key. A symbolic property does not appear in`for..in`, so it won't be occasionally listed. Also it won't be accessed directly, because anotherscriptdoes not have oursymbol, so it will not occasionally intervene into its actions.
1.Propiedades "Ocultas" dentro de un objeto.
Si queremos agregar una propiedad a un objeto que "pertenezca" a otro scriptu otra librería, podemos crear unsymboly usarlo como propiedad. Una propiedad de symbol no aparecerá en los ciclos`for..in`,por lo que no aparecerá listada. Tampoco podrá ser accesada directamente por otroscriptporque este no tendrá nuestrosymbol y no podrá intervenir en sus acciones.

So we can "covertly" hide something into objects that we need, but others should not see, using symbolic properties.
Podemos "ocultar" ciertos valores dentro de un objeto que solo estarán disponibles dentro de ese script usando las propiedades de symbol.

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 thetutorial we'll use`Symbol.iterator`for [iterables](info:iterable), `Symbol.toPrimitive`to setup [object-to-primitive conversion](info:object-toprimitive) and so on.
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, mas adelante en eltutorial, usaremos`Symbol.iterator`para [iterables](info:iterable), `Symbol.toPrimitive`para configurar [object-to-primitive conversion](info:object-toprimitive).

Technically,symbolsare 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 methods and syntax constructs adhere to a common agreement that they are. And the one who explicitly calls the aforementioned methods probably understands well what he's doing.
Técnicamente, lossymbolsno 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 retorna *todas* las propiedades 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 sintáxis se adhieren a un acuerdo común de lo que si lo están. Y el que explícitamente llama a los métodos antes mencionados probablemente entiende bien lo que está haciendo.

[8]ページ先頭

©2009-2025 Movatter.jp