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, nem booleanos, mas apenas *strings* 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, apenas utilizámos *strings*. Então, vamos ver os benefícios que *symbols* nos podem dar.
7
7
8
-
## Symbols
8
+
## Símbolos
9
9
10
-
A "symbol" represents a unique identifier.
10
+
Um "símbolo" representa um identificador único .
11
11
12
-
A value of this type can be created using`Symbol()`:
12
+
Um valor deste tipo pode ser criado usando`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
+
Quando o criamos, podemos dar ao símbolo uma descrição (também chamada de nome do símbolo), sendo ela mais útil para propósitos de *debugging* (depuração de erros):
20
20
21
-
```js
22
-
//id is a symbol with the description "id"
21
+
```js run
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, não afeta nada.
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 você tiver familiaridade com Ruby, ou outra linguagem que também tenha alguma espécie de "símbolos" -- por favor, não se confunda. Os 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
+
A maior parte dos valores em JavaScript suporta conversão implícita para *string*. Por exemplo, podemos usar `alert` com quase qualquer valor, e irá funcionar. Símbolos são especiais. Eles não são automaticamente convertidos.
43
43
44
-
For instance, this `alert` will show an error:
44
+
Por exemplo, este `alert` irá mostrar um erro:
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: Cannot convert a Symbol value to a string (ErroDeTipo: Não é possível converter um valor 'Symbol' para uma '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
+
Esta é uma "salvaguarda na linguagem" contra tal mistura, porque *strings* e *symbols* são fundamentalmente diferentes, e não deveriam ser acidentalmente convertidos de um tipo para o outro.
54
54
55
-
If we really want to show a symbol, we need to explicitly call `.toString()` on it, like here:
55
+
Se realmente quisermos exibir um *symbol*, teremos que explicitamente invocar `.toString()` sobre ele, como aqui:
Or get `symbol.description` property to show the description only:
63
+
Ou usar a propriedade `symbol.description` para mostrar apenas a sua descrição:
64
64
```js run
65
65
let id = Symbol("id");
66
66
*!*
67
-
alert(id.description); // id
67
+
alert(id.description); // 'id'
68
68
*/!*
69
69
```
70
70
71
71
````
72
72
73
-
## "Hidden" properties
73
+
## Propriedades "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
+
Símbolos nos permitem criar propriedades "ocultas" num objeto, que nenhuma outra parte do código possa acidentalmente aceder ou alterar.
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.
77
+
Por exemplo, se estivermos a trabalhar com um objeto `user`, que pertença a um código de terceiros, e quisermos adicionar identificadores a ele.
78
78
79
-
Let's use a symbol key for it:
79
+
Vamos utilizar uma chave *symbol* para isso:
80
80
81
81
```js run
82
-
let user = { //belongs to another code
82
+
let user = { //pertence a outro código
83
83
name:"John"
84
84
};
85
85
86
86
let id =Symbol("id");
87
87
88
88
user[id] =1;
89
89
90
-
alert( user[id] ); //we can access the data using the symbol as the key
90
+
alert( user[id] ); //podemos aceder aos dados usando o 'symbol' como chave (key)
91
91
```
92
92
93
-
What's the benefit of using `Symbol("id")`over a string `"id"`?
93
+
Qual o benefício de se usar `Symbol("id")`sobre uma *string*`"id"`?
94
94
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.
95
+
Como o objeto `user`pertence a outro código, e aquele código funciona bem com ele, não deveríamos sómente adicionar quaisquer propriedades a ele. Isso não é seguro. Mas, um símbolo não pode ser acedido acidentalmente, o código de terceiros provavelmente nem o irá ver, então talvez seja a coisa certa a fazer.
96
96
97
-
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.
97
+
De igual modo, imagine que ainda um outro programa (*script*) quer ter o seu próprio identificador dentro de`user`, para seus próprios fins. Isto pode estar noutra biblioteca (*library*) de JavaScript, por isso estes *scripts* podem não ter nenhum conhecimento um do outro.
98
98
99
-
Then that script can create its own `Symbol("id")`, like this:
99
+
Então, aquele programa pode criar o seu próprio `Symbol("id")`, desta forma:
100
100
101
101
```js
102
102
// ...
103
103
let id =Symbol("id");
104
104
105
-
user[id] ="Their id value";
105
+
user[id] ="O valor 'id' dos outros";
106
106
```
107
107
108
-
There will be no conflict, because symbols are always different, even if they have the same name.
108
+
Não haverá conflito entre o nosso identificador e o dos outros, porque símbolos são sempre diferentes, mesmo que tenham o mesmo nome.
109
109
110
-
Now note that if we used a string `"id"`instead of a symbol for the same purpose, then there *would* be a conflict:
110
+
...Mas, se tivéssemos usado uma *string*`"id"`em vez de um *symbol* para o mesmo propósito, então *haveria* um conflito:
111
111
112
112
```js run
113
113
let user = { name:"John" };
114
114
115
-
//Our script uses "id" property
116
-
user.id="Our id value";
115
+
//O nosso script utiliza uma propriedade "id"
116
+
user.id="O nosso valor 'id'";
117
117
118
-
// ...Another script also wants "id" for its purposes...
118
+
// ...Um outro script também quer "id" para os seus fins...
119
119
120
-
user.id="Their id value"
121
-
// Boom! overwritten by another script!
120
+
user.id="O valor 'id' dos outros"
121
+
// Boom! Alterado pelo outro script!
122
122
```
123
123
124
-
### Symbols in an object literal
124
+
### Símbolos num objeto literal
125
125
126
-
If we want to use a symbol in an object literal, we need square brackets.
126
+
Se quisermos utilizar um *symbol* num objeto literal`{...}`, precisamos de parênteses retos.
127
127
128
-
Like this:
128
+
Desta forma:
129
129
130
130
```js
131
131
let id =Symbol("id");
132
132
133
133
let user = {
134
134
name:"John",
135
135
*!*
136
-
[id]:123//not "id": 123
136
+
[id]:123//não "id": 123
137
137
*/!*
138
138
};
139
139
```
140
-
That's because we need the value from the variable`id`as the key, not the string "id".
140
+
Isto, porque precisamos do valor que está na variável`id`como chave, não da *string* "id".
141
141
142
-
### Symbols are skipped by for..in
142
+
### Símbolos são saltados num *for..in*
143
143
144
-
Symbolic properties do not participate in `for..in` loop.
144
+
Propriedades simbólicas não são consideradas num laço (*loop*) `for..in`.
145
145
146
-
For instance:
146
+
Por exemplo:
147
147
148
148
```js run
149
149
let id =Symbol("id");
@@ -154,16 +154,16 @@ let user = {
154
154
};
155
155
156
156
*!*
157
-
for (let key in user) alert(key); // name, age (no symbols)
157
+
for (let key in user) alert(key); //'name', 'age' (nenhum símbolo)
158
158
*/!*
159
159
160
-
//the direct access by the symbol works
160
+
//o acesso direto por meio do símbolo funciona
161
161
alert( "Direct: "+ user[id] );
162
162
```
163
163
164
-
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.
164
+
`Object.keys(user)` também os ignora. Isto, faz uma parte do conceito geral de "ocultação de propriedades simbólicas". Se, um outro programa ou uma biblioteca percorrer o nosso objeto com um ciclo (*loop*), não irá inadvertidamente aceder a uma propriedade simbólica.
165
165
166
-
In contrast, [Object.assign](mdn:js/Object/assign)copies both string and symbol properties:
166
+
Em contraste, [Object.assign](mdn:js/Object/assign)copia ambas as propriedades *string* e *symbol*:
167
167
168
168
```js run
169
169
let id =Symbol("id");
@@ -176,97 +176,102 @@ let clone = Object.assign({}, user);
176
176
alert( clone[id] ); // 123
177
177
```
178
178
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`).
180
-
181
-
## Global symbols
179
+
Não existe nenhum paradoxo aqui. Assim está concebido. A ideia é que ao clonar um objeto ou fundir (*merge*) objetos, geralmente queremos *todas* as propriedades copiadas (incluindo símbolos como `id`).
182
180
183
-
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.
181
+
## Símbolos globais
184
182
185
-
For instance, different parts of our application want to access symbol `"id"` meaning exactly the same property.
183
+
Como nós vimos, geralmente todos os *symbols* são diferentes, mesmo que tenham o mesmo nome. Mas, por vezes queremos que *symbols* com o mesmo nome sejam entidades únicas. Por exemplo, diferentes partes da nossa aplicação querem aceder ao *symbol*`"id"`, sendo este exatamente a mesma propriedade.
186
184
187
-
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 alcançar isto, existe um *registo global de símbolos* (*global symbol registry*). Nós podemos criar *symbols* nele e os aceder mais tarde, e ele garante que acessos repetidos ao mesmo nome retornem exatamente o mesmo *symbol*.
188
186
189
-
In order to create or read a symbol in the registry, use `Symbol.for(key)`.
187
+
Para ler (criar, se ausente) um *symbol* do registo, use `Symbol.for(key)`.
190
188
191
-
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 chamada verifica o registo global, 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`.
192
190
193
-
For instance:
191
+
Por exemplo:
194
192
195
193
```js run
196
-
//read from the global registry
197
-
let id =Symbol.for("id"); //if the symbol did not exist, it is created
194
+
//lê a partir do registo global
195
+
let id =Symbol.for("id"); //se o símbolo não existir, ele é criado
198
196
199
-
//read it again
197
+
//volta a ler (talvez a partir de outra secção no código)
200
198
let idAgain =Symbol.for("id");
201
199
202
-
//the same symbol
203
-
alert( id === idAgain ); // true
200
+
//é o mesmo símbolo
201
+
alert( id === idAgain ); // true (verdadeiro)
204
202
```
205
203
206
-
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
+
Símbolos dentro do registo são chamados de *símbolos globais* (*global symbols*). Quando queremos um *symbol* para toda a aplicação, acessível em qualquer lugar no código -- é para isso que eles servem.
207
205
208
-
```smart header="That sounds like Ruby"
209
-
In some programming languages, like Ruby, there's a single symbol per name.
206
+
```smart header="Isso parece Ruby"
207
+
Em algumas linguagens de programação, como Ruby, existe um único *symbol* por nome.
210
208
211
-
In JavaScript, as we can see, that's right for global symbols.
209
+
Em JavaScript, como podemos ver, esses são os símbolos globais.
212
210
```
213
211
214
212
### Symbol.keyFor
215
213
216
-
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 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 o nome de um símbolo global.
217
215
218
-
For instance:
216
+
Por exemplo:
219
217
220
218
```js run
219
+
// obtenha o símbolo a partir do nome
221
220
let sym =Symbol.for("name");
222
221
let sym2 =Symbol.for("id");
223
222
224
-
//get name from symbol
225
-
alert( Symbol.keyFor(sym) ); // name
226
-
alert( Symbol.keyFor(sym2) ); //id
223
+
//obtenha o nome a partir do 'symbol'
224
+
alert( Symbol.keyFor(sym) ); //'name'
225
+
alert( Symbol.keyFor(sym2) ); //'id'
227
226
```
228
227
229
-
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
+
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`.
230
229
231
-
For instance:
230
+
Deste modo, todos os símbolos têm uma propriedade `description`.
231
+
232
+
Por exemplo:
232
233
233
234
```js run
234
-
alert( Symbol.keyFor(Symbol.for("name")) ); // name, global symbol
235
+
let globalSymbol =Symbol.for("name");
236
+
let localSymbol =Symbol("name");
237
+
238
+
alert( Symbol.keyFor(globalSymbol) ); // 'name', símbolo global
239
+
alert( Symbol.keyFor(localSymbol) ); // 'undefined', não global
235
240
236
-
alert( Symbol.keyFor(Symbol("name2")) ); //undefined, the argument isn't a global symbol
241
+
alert( localSymbol.description ); //'name'
237
242
```
238
243
239
-
## System symbols
244
+
## Símbolos do sistema
240
245
241
-
There exist many "system" symbols that JavaScript uses internally, and we can use them to fine-tune various aspects of our objects.
246
+
Existem muitos símbolos do "sistema" que o JavaScript usa internamente, e nós os podemos utilizar para afinar vários aspetos dos nossos objetos.
242
247
243
-
They are listed in the specification in the [Well-known symbols](https://tc39.github.io/ecma262/#sec-well-known-symbols) table:
248
+
Eles vêm listados na especificação, na tabela [Well-known symbols](https://tc39.github.io/ecma262/#sec-well-known-symbols):
244
249
245
250
-`Symbol.hasInstance`
246
251
-`Symbol.isConcatSpreadable`
247
252
-`Symbol.iterator`
248
253
-`Symbol.toPrimitive`
249
-
- ...and so on.
254
+
- ... e assim por diante.
250
255
251
-
For instance, `Symbol.toPrimitive`allows us to describe object to primitive conversion. We'll see its use very soon.
256
+
Por exemplo, `Symbol.toPrimitive`nos permite descrever a conversão objeto-para-primitivo. Iremos ver o seu uso muito em breve.
252
257
253
-
Other symbols will also become familiar when we study the corresponding language features.
258
+
Outros *symbols* também se irão tornar familiares quando estudarmos as funcionalidades correspondentes na linguagem.
254
259
255
-
## Summary
260
+
## Resumo
256
261
257
-
`Symbol` is a primitive type for unique identifiers.
262
+
`Symbol`, é um tipo primitivo para identificadores únicos.
258
263
259
-
Symbols are created with `Symbol()` call with an optional description.
264
+
Símbolos são criados pela chamada a `Symbol()`, com uma descrição (nome) opcional.
260
265
261
-
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.
266
+
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`com a mesma `key` retornam exatamente o mesmo símbolo.
262
267
263
-
Symbols have two main use cases:
268
+
Símbolos têm dois principais casos práticos:
264
269
265
-
1. "Hidden" object properties.
266
-
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. "Ocultação" de propriedades de objetos.
271
+
Se quisermos adicionar uma propriedade a um objeto, "pertencendo" este a outro programa ou biblioteca, podemos criar um símbolo e o usar como a chave dessa propriedade. Uma propriedade simbólica não aparece num `for..in`, por isso não será acidentalmente processada juntamente com outras propriedades. Também, não será acedida diretamente, porque um outro programa não terá o nosso símbolo. Assim, a propriedade estará protegida contra uso ou alteração acidentais.
267
272
268
-
So we can "covertly" hide something into objects that we need, but others should not see, using symbolic properties.
273
+
Assim, nós podemos "secretamente" esconder nos objetos algo que precisamos, mas que outros não devam ver, empregando propriedades simbólicas.
269
274
270
-
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.Existem muitos símbolos do sistema usados pelo JavaScript que podem ser acedidos com `Symbol.*`. Podemos os utilizar para alterar alguns comportamentos pré-definidos (*built-in*). Por exemplo, mais adiante no tutorial iremos usar`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.
271
276
272
-
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.
277
+
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, assim como métodos e construções sintáticas incorporados não usam esses métodos.
0 commit comments