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
+
Segundo a especificação, as chaves das propriedades dos objetos podem ser quer do tipo *string* como do tipo *symbol*. Não números, não booleanos, apenas *strings* (cadeias-de-carateres) ou *symbols* (símbolos), estes dois tipos.
5
5
6
-
Till now we've been using only strings. Now let's see the benefits that symbols can give us.
6
+
Até agora, vimos apenas utilizando *strings*. Então, vejamos os benefícios que *symbols* nos dão.
7
7
8
-
## Symbols
8
+
## Símbolos
9
9
10
-
A "symbol" represents a unique identifier.
10
+
Um "símbolo" representa um único identicador.
11
11
12
-
A value of this type can be created using`Symbol()`:
12
+
Um valor deste tipo, pode ser criado utilizando`Symbol()`:
13
13
14
14
```js
15
-
//id is a new symbol
15
+
//'id' é um novo símbolo
16
16
let id =Symbol();
17
17
```
18
18
19
-
We can also give symbol a description (also called a symbol name), mostly useful for debugging purposes:
19
+
Podemos também dar ao símbolo uma descrição (igualmente chamada de nome do símbolo), sendo mais útil para fins de *debugging* (depuração de erros):
20
20
21
21
```js run
22
-
//id is a symbol with the description "id"
22
+
//'id' é um símbolo com a descrição "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
+
Símbolos têm a garantia de serem únicos. Mesmo que criemos muitos símbolos com a mesma descrição, eles são valores diferentes. A descrição apenas é um rótulo, sem efeito algum.
27
27
28
-
For instance, here are two symbols with the same description -- they are not equal:
28
+
Por exemplo, aqui estão dois símbolos com a mesma descrição -- eles não são iguais:
29
29
30
30
```js run
31
31
let id1 =Symbol("id");
32
32
let id2 =Symbol("id");
33
33
34
34
*!*
35
-
alert(id1 == id2); // false
35
+
alert(id1 == id2); // false (falso)
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
+
Se tiver familiaridade com Ruby ou outra linguagem que também empregue algum tipo de "símbolos" -- por favor, não se confunda. Símbolos em JavaScript são 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="Símbolos não são auto-convertidos para strings"
42
+
Muitos valores em JavaScript suportam conversão implícita para *string*. Por exemplo, podemos usar `alert` com quase qualquer valor, e funcionará. Símbolos são especiais. Não há auto-conversão.
43
43
44
-
For instance, this `alert` will show an error:
44
+
Por exemplo, este `alert` exibirá um erro:
45
45
46
46
```js run
47
47
let id = Symbol("id");
48
48
*!*
49
49
alert(id); // TypeError: Cannot convert a Symbol value to a string
50
+
// TypeError: Não é possível converter um valor 'Symbol' para uma 'string'
50
51
*/!*
51
52
```
52
53
53
-
That's a "language guard" against messing up, because strings and symbols are fundamentally different and should not occasionally convert one into another.
54
+
Existe uma "salvaguarda na linguagem" contra a mistura de ambos, porque *strings* e *symbols* são fundamentalmente diferentes, e não deveriam ser convertidos de um tipo para o outro ao acaso.
54
55
55
-
If we really want to show a symbol, we need to explicitly call `.toString()` on it, like here:
56
+
Se realmente quisermos exibir um *symbol*, temos que explicitamente invocar `.toString()` sobre ele, como aqui:
Or get `symbol.description` property to show the description only:
64
+
Ou empregar a propriedade `symbol.description` para apenas mostrar a sua descrição:
64
65
```js run
65
66
let id = Symbol("id");
66
67
*!*
67
-
alert(id.description); // id
68
+
alert(id.description); // 'id'
68
69
*/!*
69
70
```
70
71
71
72
````
72
73
73
-
## "Hidden" properties
74
+
## Propriedades "Ocultas"
74
75
75
-
Symbols allow us to create "hidden" properties of an object, that no other part of code can occasionally access or overwrite.
76
+
Símbolos permitem-nos criar propriedades "ocultas" para um objeto, que nenhuma outra parte do código as possa aceder ou alterar.
76
77
77
-
<<<<<<< HEAD
78
-
For instance, if we want to store an "identifier" for the object `user`, we can use a symbol as a key for it:
79
-
=======
80
-
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
+
Por exemplo, se estivermos a trabalhar com objetos `user`, que pertençam a código de terceiros. E queremos de adicionar identicadores a eles.
81
79
82
-
Let's use a symbol key for it:
83
-
>>>>>>> 852ee189170d9022f67ab6d387aeae76810b5923
80
+
Vamos utilizar uma chave *symbol* para isso:
84
81
85
82
```js run
86
-
let user = { //belongs to another code
83
+
let user = { //pertence a outro código
87
84
name:"John"
88
85
};
89
86
90
87
let id =Symbol("id");
91
88
92
89
user[id] =1;
93
90
94
-
alert( user[id] ); //we can access the data using the symbol as the key
91
+
alert( user[id] ); //podemos aceder aos dados usando o 'symbol' como chave (key)
95
92
```
96
93
97
-
What's the benefit of using `Symbol("id")`over a string `"id"`?
94
+
Qual o benefício de se usar `Symbol("id")`sobre uma *string*`"id"`?
98
95
99
-
Let's make the example a bit deeper to see that.
96
+
Façamos um exemplo um pouco mais aprofundado para o vermos.
100
97
101
-
Imagine that another script wants 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.
98
+
Imagine que um outro programa (*script*) quer a sua própria propriedade "id" dentro de`user`, para seus próprios fins. Isto pode estar noutra biblioteca (*library*) de JavaScript, por isso os *scripts* podem não ter nenhum conhecimento um do outro.
102
99
103
-
Then that script can create its own `Symbol("id")`, like this:
100
+
Então, aquele programa pode criar o seu próprio `Symbol("id")`, desta forma:
104
101
105
102
```js
106
103
// ...
107
104
let id =Symbol("id");
108
105
109
-
user[id] ="Their id value";
106
+
user[id] ="O seu 'id' é válido";
110
107
```
111
108
112
-
There will be no conflict, because symbols are always different, even if they have the same name.
109
+
Não haverá conflito, porque símbolos são sempre diferentes, mesmo que tenham o mesmo nome.
113
110
114
-
Now note that if we used a string `"id"`instead of a symbol for the same purpose, then there *would* be a conflict:
111
+
Agora, note que se tivéssemos empregue uma *string*`"id"`em vez de um *symbol* para o mesmo propósito, então *haveria* um conflito:
115
112
116
113
```js run
117
114
let user = { name:"John" };
118
115
119
-
//Our script uses "id" property
120
-
user.id="Our id value";
116
+
//O nosso script utiliza uma propriedade "id"
117
+
user.id="O nosso valor 'id'";
121
118
122
-
// ...Another script also wants "id" for its purposes...
119
+
// ...Um outro script também quer "id" para os seus fins...
123
120
124
-
user.id="Their id value"
125
-
// Boom! overwritten by another script!
121
+
user.id="O seu valor 'id'"
122
+
// Boom! Alterado pelo outro script!
126
123
```
127
124
128
-
### Symbols in a literal
125
+
### Símbolos num literal
129
126
130
-
If we want to use a symbol in an object literal, we need square brackets.
127
+
Se quisermos utilizar um *symbol* num objeto literal, precisamos de parênteses retos.
131
128
132
-
Like this:
129
+
Desta forma:
133
130
134
131
```js
135
132
let id =Symbol("id");
136
133
137
134
let user = {
138
135
name:"John",
139
136
*!*
140
-
[id]:123//not "id: 123"
137
+
[id]:123//não "id: 123"
141
138
*/!*
142
139
};
143
140
```
144
-
That's because we need the value from the variable `id` as the key, not the string "id".
145
141
146
-
### Symbols are skipped by for..in
142
+
Isto, porque precisamos do valor que está na variável `id` como chave (*key*), não da *string* "id".
147
143
148
-
Symbolic properties do not participate in `for..in` loop.
144
+
### Símbolos são saltados num *for..in*
149
145
150
-
For instance:
146
+
Propriedades simbólicas não são consideradas num laço (*loop*) `for..in`.
147
+
148
+
Por exemplo:
151
149
152
150
```js run
153
151
let id =Symbol("id");
@@ -158,16 +156,16 @@ let user = {
158
156
};
159
157
160
158
*!*
161
-
for (let key in user) alert(key); // name, age (no symbols)
159
+
for (let key in user) alert(key); //'name', 'age' (nenhum símbolo)
162
160
*/!*
163
161
164
-
//the direct access by the symbol works
162
+
//o acesso direto por meio do símbolo funciona
165
163
alert( "Direct: "+ user[id] );
166
164
```
167
165
168
-
That's a part of the general "hiding" concept. If another script or a library loops over our object, it won't unexpectedly access a symbolic property.
166
+
Isto, é uma parte do conceito geral de "ocultação". Se, um outro programa (*script*) ou uma biblioteca (*library*) percorrer o nosso objeto com um ciclo (*loop*), não irá inadvertidamente aceder a uma propriedade simbólica.
169
167
170
-
In contrast, [Object.assign](mdn:js/Object/assign)copies both string and symbol properties:
168
+
Em contraste, [Object.assign](mdn:js/Object/assign)copia ambas as propriedades *string* e *symbol*:
171
169
172
170
```js run
173
171
let id =Symbol("id");
@@ -180,113 +178,114 @@ let clone = Object.assign({}, user);
180
178
alert( clone[id] ); // 123
181
179
```
182
180
183
-
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`).
181
+
Não existe nenhum paradoxo aqui. Esse é o propósito. A ideia é que ao clonar ou fundir objetos, queremos geralmente *todas* as propriedades copiadas (incluindo símbolos como`id`).
184
182
185
-
````smart header="Property keys of other types are coerced to strings"
186
-
We can only use strings or symbols as keys in objects. Other types are converted to strings.
183
+
````smart header="Chaves de propriedades de outros tipos são convertidas para strings"
184
+
Podemos apenas utilizar *strings* ou *symbols* como chaves em objetos. Outros tipos são forçados para *strings*.
187
185
188
-
For instance, a number `0` becomes a string `"0"` when used as a property key:
186
+
Por exemplo, um número `0` torna-se numa *string* `"0"` quando usado como chave de uma propriedade:
189
187
190
188
```js run
191
189
let obj = {
192
-
0: "test" // same as "0": "test"
190
+
0: "test" // o mesmo que "0": "test"
193
191
};
194
192
195
-
// both alerts access the same property (the number 0 is converted to string "0")
193
+
// ambos os *alerts* acedem à mesma propriedade (o número 0 é convertido para a *string* "0")
196
194
alert( obj["0"] ); // test
197
-
alert( obj[0] ); // test (same property)
195
+
alert( obj[0] ); // test (a mesma propriedade)
198
196
```
199
197
````
200
198
201
-
## Global symbols
199
+
## Símbolos globais
202
200
203
-
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.
201
+
Como vimos, geralmente todos os *symbols* são diferentes, mesmo que tenham o mesmo nome. Mas, por vezes queremos que *symbols* com o mesmo nome se refiram às mesmas entidades.
204
202
205
-
For instance, different parts of our application want to access symbol `"id"` meaning exactly the same property.
203
+
Por exemplo, diferentes partes na nossa aplicação pretendem aceder ao *symbol*`"id"`, significando este uma única mesma propriedade.
206
204
207
-
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.
205
+
Para alcançar isso, existe um *registo global de símbolos* (*global symbol registry*). Podemos criar *symbols* nele e acedê-los mais tarde, e ele garante que acessos repetidos ao mesmo nome retornem exatamente o mesmo *symbol*.
208
206
209
-
In order to create or read a symbol in the registry, use `Symbol.for(key)`.
207
+
Para criar e ler um *symbol* do registo, use `Symbol.for(key)`.
210
208
211
-
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`.
209
+
Essa chamada verifica o registo global (*global registry*), e se houver um *symbol* descrito como`key`, ele o retorna, senão cria um novo *symbol* com `Symbol(key)`e o armazena no registo sob a chave`key`.
212
210
213
-
For instance:
211
+
Por exemplo:
214
212
215
213
```js run
216
-
//read from the global registry
217
-
let id =Symbol.for("id"); //if the symbol did not exist, it is created
214
+
//lê a partir do registo global
215
+
let id =Symbol.for("id"); //se o símbolo não existir, ele o cria
218
216
219
-
//read it again
217
+
//volta a ler
220
218
let idAgain =Symbol.for("id");
221
219
222
-
//the same symbol
223
-
alert( id === idAgain ); // true
220
+
//é o mesmo símbolo
221
+
alert( id === idAgain ); // true (verdadeiro)
224
222
```
225
223
226
-
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.
224
+
Símbolos dentro do registo são chamados de *símbolos globais* (*global symbols*). Quando quisermos um *symbol* para toda a aplicação, acessível em qualquer parte do código -- é para o que eles servem.
227
225
228
-
```smart header="That sounds like Ruby"
229
-
In some programming languages, like Ruby, there's a single symbol per name.
226
+
```smart header="Isto parece Ruby"
227
+
Em algumas linguagens de programação, como Ruby, existe um único *symbol* por nome.
230
228
231
-
In JavaScript, as we can see, that's right for global symbols.
229
+
Em JavaScript, como podemos ver, esses são símbolos globais.
232
230
```
233
231
234
232
### Symbol.keyFor
235
233
236
-
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.
234
+
Para símbolos globais, não apenas`Symbol.for(key)`retorna um *symbol* por nome, mas existe uma chamada inversa: `Symbol.keyFor(sym)`, que faz ao contrário - retorna um nome de um símbolo global.
237
235
238
-
For instance:
236
+
Por exemplo:
239
237
240
238
```js run
241
239
let sym =Symbol.for("name");
242
240
let sym2 =Symbol.for("id");
243
241
244
-
//get name from symbol
245
-
alert( Symbol.keyFor(sym) ); // name
246
-
alert( Symbol.keyFor(sym2) ); //id
242
+
//Obtenha o nome do 'symbol'
243
+
alert( Symbol.keyFor(sym) ); //'name'
244
+
alert( Symbol.keyFor(sym2) ); //'id'
247
245
```
248
246
249
-
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 return`undefined`.
247
+
O`Symbol.keyFor`utiliza internamente o registo global de símbolos para procurar pela chave do símbolo. Por isso, não funciona para símbolos não globais. Se o símbolo não for global, não será capaz de o encontrar e retorna`undefined`.
250
248
251
-
For instance:
249
+
Por exemplo:
252
250
253
251
```js run
254
-
alert( Symbol.keyFor(Symbol.for("name")) ); // name, global symbol
252
+
alert( Symbol.keyFor(Symbol.for("name")) ); //'name', símbolo global
255
253
256
-
alert( Symbol.keyFor(Symbol("name2")) ); // undefined, the argument isn't a global symbol
254
+
alert( Symbol.keyFor(Symbol("name2")) ); // undefined, o argumento não é um símbolo global
257
255
```
258
256
259
-
## System symbols
257
+
## Símbolos do sistema
260
258
261
-
There exist many "system" symbols that JavaScript uses internally, and we can use them to fine-tune various aspects of our objects.
259
+
Existem muitos símbolos do "sistema" que o JavaScript usa internamente, e os podemos utilizar para afinar vários aspetos dos nossos objetos.
262
260
263
-
They are listed in the specification in the [Well-known symbols](https://tc39.github.io/ecma262/#sec-well-known-symbols) table:
261
+
Eles vêm listados na especificação, na tabela [Well-known symbols](https://tc39.github.io/ecma262/#sec-well-known-symbols):
264
262
265
263
-`Symbol.hasInstance`
266
264
-`Symbol.isConcatSpreadable`
267
265
-`Symbol.iterator`
268
266
-`Symbol.toPrimitive`
269
-
- ...and so on.
267
+
- ... e assim por diante.
268
+
269
+
Por exemplo, `Symbol.toPrimitive` permite-nos descrever a conversão objeto-para-primitivo. Veremos o seu uso muito em breve.
270
270
271
-
For instance, `Symbol.toPrimitive` allows us to describe object to primitive conversion. We'll see its use very soon.
271
+
Outros *symbols* também se tornarão familiares quando estudarmos as funcionalidades correspondentes na linguagem.
272
272
273
-
Other symbols will also become familiar when we study the corresponding language features.
273
+
## Sumário
274
274
275
-
## Summary
275
+
`Symbol`, é um tipo primitivo para identicadores únicos.
276
276
277
-
`Symbol` is a primitive type for unique identifiers.
277
+
Símbolos são criados pela chamada a `Symbol()`, com uma descrição opcional.
278
278
279
-
Symbols are created with `Symbol()`call with an optional description.
279
+
Símbolos são sempre valores diferentes, mesmo que tenham o mesmo nome. Se quisermos que símbolos com o mesmo nome sejam iguais, teremos de utilizar o registo global: `Symbol.for(key)`retorna (cria, se necessário) um símbolo global com `key` como nome. Múltiplas chamadas a `Symbol.for` retornam exatamente o mesmo símbolo.
280
280
281
-
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` return exactly the same symbol.
281
+
Símbolos têm dois principais casos práticos:
282
282
283
-
Symbols have two main use cases:
283
+
1. "Ocultação" de propriedades de objetos.
284
284
285
-
1. "Hidden" object properties.
286
-
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 occasionally listed. Also it won't be accessed directly, because another script does not have our symbol, so it will not occasionally intervene into its actions.
285
+
Se quisermos adicionar uma propriedade a um objeto que "peetença" a outro programa ou biblioteca, podemos criar um símbolo e o utilizar como a chave da propriedade. Uma propriedade simbólica não aparece num `for..in`, por isso em certas ocasiões não será listada. Também, não será diretamente acedida porque outro programa não terá o nosso símbolo, e portanto não irá inadvertidamente intervir nas suas ações .
287
286
288
-
So we can "covertly" hide something into objects that we need, but others should not see, using symbolic properties.
287
+
Assim, podemos "secretamente" esconder em objetos algo que precisemos, e que outros não possam ver, empregando propriedades simbólicas.
289
288
290
-
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.
289
+
2.Existem muitos símbolos de sistema usados por JavaScript que podem ser acedidos com `Symbol.*`. Podemos os utilizar para alterar alguns comportamentos padrão (*built-in*). Por exemplo, mais adiante no tutorial usaremos `Symbol.iterator`para[iterables](info:iterable) (iteráveis), `Symbol.toPrimitive`para configurar a [object-to-primitive conversion](info:object-toprimitive)(conversão objeto-para-primitivo), e assim por diante.
291
290
292
-
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 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.
291
+
Tecnicamente, símbolos não são 100% ocultados. Existe um método incorporado (*built-in*) [Object.getOwnPropertySymbols(obj)](mdn:js/Object/getOwnPropertySymbols)que nos permite obter todos os símbolos. Também, existe um método chamado [Reflect.ownKeys(obj)](mdn:js/Reflect/ownKeys)que retorna *todas* as chaves de um objeto, incluindo as simbólicas. Assim, eles não estão realmente ocultos. Mas muitas bibliotecas, métodos e construções sintáticas incorporados aderem ao comum acordo de que estão. E, quem invocar os métodos agora mencionados provavelmente compreende bem o que está a fazer.
0 commit comments