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
Por especificação, apenas dois tipos primitivos podem ser utilizados como chaves de propriedades de objetos:
3
4
4
-
By specification, only two primitive types may serve as object property keys:
5
+
- o tipo string, ou
6
+
- o tipo symbol.
5
7
6
-
- string type, or
7
-
- symbol type.
8
+
Caso contrário, se for usado outro tipo, como o tipo number, ele é convertido automaticamente para string. Assim `obj[1]` é o mesmo que `obj["1"]`, e `obj[true]` é o mesmo que `obj["true"]`
8
9
9
-
Otherwise, if one uses another type, such as number, it's autoconverted to string. So that `obj[1]` is the same as `obj["1"]`, and `obj[true]` is the same as `obj["true"]`.
10
+
Até agora, só temos utilizado strings.
10
11
11
-
Until now we've been using only strings.
12
-
13
-
Now let's explore symbols, see what they can do for us.
12
+
Agora vamos explorar os symbols e ver o que eles podem fazer por nós.
14
13
15
14
## Symbols
16
15
17
-
A "symbol" represents a unique identifier.
16
+
Um "symbol" representa um identificador único.
18
17
19
-
A value of this type can be created using`Symbol()`:
18
+
Um valor desse tipo pode ser criado usando`Symbol()`:
20
19
21
20
```js
22
21
let id =Symbol();
23
22
```
24
23
25
-
Upon creation, we can give symbols a description (also called a symbol name), mostly useful for debugging purposes:
24
+
Ao criá-los, podemos atribuir aos symbols uma descrição (também conhecida como nome do symbol), geralmente útil para fins de depuração:
26
25
27
26
```js
28
-
// id is a symbol with the description "id"
27
+
// id é um symbol com a descrição "id"
29
28
let id =Symbol("id");
30
29
```
31
30
32
-
Symbols are guaranteed to be unique. Even if we create many symbols with exactly the same description, they are different values. The description is just a label that doesn't affect anything.
31
+
Symbols são garantidos como únicos. Mesmo que criemos muitos symbols com exatamente a mesma descrição, eles são valores diferentes. A descrição é apenas um rótulo que não afeta nada.
33
32
34
-
For instance, here are two symbols with the same description -- they are not equal:
33
+
Por exemplo, aqui estão dois symbols com a mesma descrição -- eles não são iguais:
35
34
36
35
```js run
37
36
let id1 =Symbol("id");
@@ -42,14 +41,14 @@ alert(id1 == id2); // false
42
41
*/!*
43
42
```
44
43
45
-
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.
44
+
Se você estiver familiarizado com Ruby ou outra linguagem que também tenha algum tipo de "symbols", por favor, não se deixe confundir. Symbols no JavaScript são diferentes.
46
45
47
-
So, to summarize, a symbol is a "primitive unique value" with an optional description. Let's see where we can use them.
46
+
Então, para resumir, um symbol é um "valor primitivo único" com uma descrição opcional. Vamos ver onde podemos usá-los.
48
47
49
-
````warn header="Symbols don't auto-convert to a string"
50
-
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.
48
+
````warn header="Symbols não são automaticamente convertidos para uma string"
49
+
A maioria dos valores no JavaScript suporta conversão implícita para string. Por exemplo, podemos usar `alert` com quase qualquer valor, e isso funcionará. Symbols são especiais, pois não são convertidos automaticamente para uma string.
51
50
52
-
For instance, this `alert` will show an error:
51
+
Por exemplo, esse `alert` vai mostrar um erro:
53
52
54
53
```js run
55
54
let id = Symbol("id");
@@ -58,18 +57,18 @@ alert(id); // TypeError: Cannot convert a Symbol value to a string
58
57
*/!*
59
58
```
60
59
61
-
That's a "language guard" against messing up, because strings and symbols are fundamentally different and should not accidentally convert one into another.
60
+
Isso serve como um "guardião da linguagem" contra confusões, uma vez que strings e symbols são fundamentalmente diferentes e não devem ser convertidos acidentalmente um no outro.
62
61
63
-
If we really want to show a symbol, we need to explicitly call `.toString()` on it, like here:
62
+
Se realmente queremos exibir um symbol, precisamos chamá-lo explicitamente com `.toString()`, como mostrado aqui:
Or get `symbol.description` property to show the description only:
71
+
Ou podemos obter a propriedade `symbol.description` para exibir apenas a descrição:
73
72
74
73
```js run
75
74
let id = Symbol("id");
@@ -80,34 +79,34 @@ alert(id.description); // id
80
79
81
80
````
82
81
83
-
## "Hidden" properties
84
-
82
+
## Propriedades "Ocultas"
85
83
86
-
Symbols allow us to create "hidden" properties of an object, that no other part of code can accidentally access or overwrite.
84
+
Symbols nos permitem criar propriedades "ocultas" de um objecto, as quais nenhuma outra parte do código pode acessar ou sobrescrever acidentalmente.
87
85
88
-
For instance, if we're working with `user`objects, that belong to a third-party code. We'd like to add identifiers to them.
86
+
Por exemplo, se estivermos trabalhando com objetos `user`que pertencem a um código de terceiros, gostaríamos de adicionar identificadores a eles.
89
87
90
-
Let's use a symbol key for it:
88
+
Vamos usar uma chave do tipo symbol para isso:
91
89
92
90
```js run
93
-
let user = { // belongs to another code
94
-
name:"John"
91
+
let user = {
92
+
// pertence a outro código
93
+
name:"John",
95
94
};
96
95
97
96
let id =Symbol("id");
98
97
99
98
user[id] =1;
100
99
101
-
alert(user[id]); //we can access the data using the symbol as the key
100
+
alert(user[id]); //podemos acessar os dados usando symbol como chave
102
101
```
103
102
104
-
What's the benefit of using`Symbol("id")`over a string `"id"`?
103
+
Qual o benefício de usar`Symbol("id")`ao invés de uma string `"id"`?
105
104
106
-
As `user`objects belong to another codebase, it's unsafe to add fields to them, since we might affect pre-defined behavior in that other codebase. However, symbols cannot be accessed accidentally. The third-party code won't be aware of newly defined symbols, so it's safe to add symbols to the`user` objects.
105
+
Como os objetos `user`pertencem a outra base de código, não é seguro adicionar campos a eles, pois podemos afetar o comportamento pré-definido nessa outra base de código. No entanto, symbols não podem ser acessados acidentalmente. O código de terceiros não estará ciente da existência de symbols recém-definidos, portanto, é seguro adicionar symbols aos objetos`user`.
107
106
108
-
Also, imagine that another script wants to have its own identifier inside`user`, for its own purposes.
107
+
Além disso, imagine que outro script deseja ter seu próprio identificador dentro de`user`, para seus próprios propósitos.
109
108
110
-
Then that script can create its own`Symbol("id")`, like this:
109
+
Então esse script pode criar seu próprio`Symbol("id")`, dessa forma:
111
110
112
111
```js
113
112
// ...
@@ -116,45 +115,46 @@ let id = Symbol("id");
116
115
user[id] ="Their id value";
117
116
```
118
117
119
-
There will be no conflict between our and their identifiers, because symbols are always different, even if they have the same name.
118
+
Não haverá conflito entre os nossos idenficadores e os deles, porque symbols são sempre diferentes, mesmo que tenham o mesmo nome.
120
119
121
-
...But if we used a string `"id"`instead of a symbol for the same purpose, then there *would* be a conflict:
120
+
...Porém se usarmos uma string `"id"`ao invés de um symbol para o mesmo propósito, então _haverá_ um conflito:
122
121
123
122
```js
124
123
let user = { name:"John" };
125
124
126
-
//Our script uses "id" property
125
+
//Nosso script usa a propriedade "id"
127
126
user.id="Our id value";
128
127
129
-
// ...Another script also wants "id" for its purposes...
128
+
// ...Outro script também quer usar a propriedade "id" para os seus fins...
130
129
131
-
user.id="Their id value"
132
-
// Boom! overwritten by another script!
130
+
user.id="Their id value";
131
+
// Boom! Sobrescrito por outro script!
133
132
```
134
133
135
-
### Symbols in an object literal
134
+
### Symbols em uma notação literal de objeto
136
135
137
-
If we want to use a symbol in an object literal `{...}`, we need square brackets around it.
136
+
Se quisermos usar um symbol em uma notação literal de objeto `{...}`, precisamos de colchetes ao redor dele.
138
137
139
-
Like this:
138
+
Assim:
140
139
141
140
```js
142
141
let id =Symbol("id");
143
142
144
143
let user = {
145
144
name:"John",
146
145
*!*
147
-
[id]:123//not "id": 123
146
+
[id]:123//não "id": 123
148
147
*/!*
149
148
};
150
149
```
151
-
That's because we need the value from the variable `id` as the key, not the string "id".
152
150
153
-
### Symbols are skipped by for..in
151
+
Isso ocorre porque precisamos do valor da variavel `id` como chave, não a string "id".
152
+
153
+
### Symbols são ignorados pelo for..in
154
154
155
-
Symbolic properties do not participate in`for..in` loop.
155
+
Propriedades simbólicas não participam do loop`for..in`.
156
156
157
-
For instance:
157
+
Por exemplo:
158
158
159
159
```js run
160
160
let id =Symbol("id");
@@ -165,125 +165,125 @@ let user = {
165
165
};
166
166
167
167
*!*
168
-
for (let key in user) alert(key); // name, age (no symbols)
168
+
for (let key in user) alert(key); // name, age (sem symbols)
169
169
*/!*
170
170
171
-
//the direct access by the symbol works
171
+
//o acesso direto por meio do symbol funciona
172
172
alert( "Direct: "+ user[id] ); // Direct: 123
173
173
```
174
174
175
-
[Object.keys(user)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)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.
175
+
[Object.keys(user)](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)também as ignora. Isso faz parte do princípio geral de "esconder propriedades simbólicas". Se outro script ou uma biblioteca percorrer o nosso objeto, não acessará inesperadamente uma propriedade simbólica.
176
176
177
-
In contrast, [Object.assign](mdn:js/Object/assign)copies both string and symbol properties:
177
+
Em contraste, [Object.assign](mdn:js/Object/assign)copia tanto as propriedades da string quanto as do symbol.
178
178
179
179
```js run
180
180
let id =Symbol("id");
181
181
let user = {
182
-
[id]:123
182
+
[id]:123,
183
183
};
184
184
185
185
let clone =Object.assign({}, user);
186
186
187
-
alert(clone[id]); // 123
187
+
alert(clone[id]); // 123
188
188
```
189
189
190
-
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`).
190
+
Não existe paradoxo aqui. Isso foi projetado dessa forma. A ideia é que, ao clonar um objeto ou mesclar objetos, geralmente queremos que _todas_ as propriedade sejam copiadas (incluindo symbols como`id`).
191
191
192
-
## Global symbols
192
+
## Symbols globais
193
193
194
-
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.
194
+
Como vimos, normalmente, todos os symbols são diferentes, mesmo que tenham o mesmo nome. Porém, às vezes, queremos que symbols com o mesmo nome representem as mesmas entidades. Por exemplo, diferentes partes da nossa aplicação podem querer acessar o symbol `"id"`, significando exatamente a mesma propriedade.
195
195
196
-
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.
196
+
Para alcançar isso, existe um _registro global de symbols_. Podemos criar symbols nele e acessá-los posteriormente, garantindo que acessos repetidos pelo mesmo nome retornem exatamente o mesmo symbol.
197
197
198
-
In order to read (create if absent) a symbol from the registry, use `Symbol.for(key)`.
198
+
Para ler (ou criar se ausente) um symbol do registro, use `Symbol.for(chave)`.
199
199
200
-
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`.
200
+
Esta chamada verifica o registro global e, se existir um symbol descrito como `chave`, o retorna; caso contrário, cria um novo symbol `Symbol(chave)`e o armazena no registro com `chave` fornecida.
201
201
202
-
For instance:
202
+
Por exemplo:
203
203
204
204
```js run
205
-
//read from the global registry
206
-
let id =Symbol.for("id"); //if the symbol did not exist, it is created
205
+
//lê do registro global
206
+
let id =Symbol.for("id"); //se o symbol não existir, ele é criado
207
207
208
-
//read it again (maybe from another part of the code)
208
+
//lê novamente (talvez de alguma outra parte do código)
209
209
let idAgain =Symbol.for("id");
210
210
211
-
//the same symbol
212
-
alert(id === idAgain); // true
211
+
//o mesmo symbol
212
+
alert(id === idAgain); // true
213
213
```
214
214
215
-
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.
215
+
Symbols dentro do registro são chamados de _symbols globais_. Se quisermos um symbol de escopo global na aplicação, acessível em todos os lugares do código, é para isso que eles servem.
216
216
217
-
```smart header="That sounds like Ruby"
218
-
In some programming languages, like Ruby, there's a single symbol per name.
217
+
```smart header="Isso parece com Ruby"
218
+
Em algumas linguagens de programação, como no Ruby, há um único symbol por nome.
219
219
220
-
In JavaScript, as we can see, that's true for global symbols.
220
+
Em JavaScript, como podemos ver, isso é verdade para symbols globais.
221
221
```
222
222
223
223
### Symbol.keyFor
224
224
225
-
We have seen that for global symbols, `Symbol.for(key)`returns a symbol by name. To do the opposite -- return a name by global symbol -- we can use: `Symbol.keyFor(sym)`:
225
+
Nós vimos que, para symbols globais, `Symbol.for(chave)`retorna um symbol pelo nome. Para fazer o oposto -- retornar um nome pelo symbol global -- podemos usar: `Symbol.keyFor(sym)`:
226
226
227
-
For instance:
227
+
Por exemplo:
228
228
229
229
```js run
230
-
//get symbol by name
230
+
//obtém o symbol pelo nome
231
231
let sym =Symbol.for("name");
232
232
let sym2 =Symbol.for("id");
233
233
234
-
//get name by symbol
235
-
alert(Symbol.keyFor(sym)); // name
236
-
alert(Symbol.keyFor(sym2)); // id
234
+
//obtém o nome pelo symbol
235
+
alert(Symbol.keyFor(sym)); // name
236
+
alert(Symbol.keyFor(sym2)); // id
237
237
```
238
238
239
-
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`.
239
+
O`Symbol.keyFor`utiliza internamente o registro global de symbols para procurar a chave associada ao symbol. Portanto, não funciona para symbols não globais. Se o symbol não for global, não será possível encontrá-lo, e a função retornará `undefined`
240
240
241
-
That said, all symbols have the `description` property.
241
+
Dito isso, todos os symbols têm a propriedade `description`
242
242
243
-
For instance:
243
+
Por exemplo:
244
244
245
245
```js run
246
246
let globalSymbol =Symbol.for("name");
247
247
let localSymbol =Symbol("name");
248
248
249
-
alert(Symbol.keyFor(globalSymbol)); // name, global symbol
250
-
alert(Symbol.keyFor(localSymbol)); // undefined, not global
249
+
alert(Symbol.keyFor(globalSymbol)); // name, symbol global
250
+
alert(Symbol.keyFor(localSymbol)); // undefined, não global
251
251
252
-
alert(localSymbol.description); // name
252
+
alert(localSymbol.description); // name
253
253
```
254
254
255
-
## System symbols
255
+
## Symbols do sistema
256
256
257
-
There exist many "system" symbols that JavaScript uses internally, and we can use them to fine-tune various aspects of our objects.
257
+
Existem muitos symbols "do sistema" (System symbols) que o JavaScript usa internamente, e podemos utilizá-los para ajustar vários aspectos dos nossos objetos.
258
258
259
-
They are listed in the specification in the[Well-known symbols](https://tc39.github.io/ecma262/#sec-well-known-symbols) table:
259
+
Eles estão listados na especificação na tabela de[Well-known symbols](https://tc39.github.io/ecma262/#sec-well-known-symbols):
260
260
261
-
-`Symbol.hasInstance`
261
+
-`Symbol.hasInstance`:
262
262
-`Symbol.isConcatSpreadable`
263
263
-`Symbol.iterator`
264
264
-`Symbol.toPrimitive`
265
-
- ...and so on.
265
+
- ...e assim por diante.
266
266
267
-
For instance, `Symbol.toPrimitive`allows us to describe object to primitive conversion. We'll see its use very soon.
267
+
Por exemplo, `Symbol.toPrimitive`nos permite descrever a conversão de um objeto para um primitivo. Veremos seu uso muito em breve.
268
268
269
-
Other symbols will also become familiar when we study the corresponding language features.
269
+
Outros symbols também se tornarão familiares à medida que estudarmos as características correspondentes da linguagem.
270
270
271
-
## Summary
271
+
## Resumo
272
272
273
-
`Symbol`is a primitive type for unique identifiers.
273
+
`Symbol`é um tipo primitivo para identificadores ínicos.
274
274
275
-
Symbols are created with `Symbol()`call with an optional description (name).
275
+
Symbols são criados com a chamada `Symbol()`com uma descrição opcional (nome).
276
276
277
-
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.
277
+
Symbols são sempre valores diferentes, mesmo se tiverem o mesmo nome. Se desejamos que symbols com o mesmo nome sejam iguals, então devemos usar o registro global: `Symbol.for(chave)`retorna (cria, se necessário) um symbol global com `chave` como nome. Múltiplas chamadas de`Symbol.for`com a mesma `chave` return exatamente o mesmo symbol.
278
278
279
-
Symbols have two main use cases:
279
+
Symbols têm dois principais casos de uso:
280
280
281
-
1."Hidden" object properties.
281
+
1.Propriedades "ocultas" de objetos.
282
282
283
-
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.
283
+
Se desejamos adicionar uma propriedade a um objeto que "pertence" a outro script ou biblioteca, podemos criar um símbolo e usá-lo como chave de propriedade. Uma propriedade simbólica não aparece em for..in, portanto, não será processada acidentalmente junto com outras propriedades. Além disso, ela não será acessada diretamente, porque outro script não possui o nosso símbolo. Assim, a propriedade estará protegida contra uso ou sobrescrita acidental.
284
284
285
-
So we can "covertly" hide something into objects that we need, but others should not see, using symbolic properties.
285
+
Portanto, podemos "ocultar discretamente" algo em objetos que precisamos, mas que outros não devem ver, usando propriedades simbólicas.
286
286
287
-
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.
287
+
2.Existem muitos símbolos do sistema usados pelo JavaScript que são acessíveis como`Symbol.*`. Podemos utilizá-los para alterar alguns comportamentos embutidos. Por exemplo, mais tarde no tutorial, utilizaremos `Symbol.iterator`para [iteráveis](info:iterable), `Symbol.toPrimitive`para configurar [conversão de objeto para primitivo](info:object-toprimitive)e assim por diante.
288
288
289
-
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. But most libraries, built-in functions and syntax constructs don't use these methods.
289
+
Tecnicamente, symbols nao são 100% ocultos. Existe um método embutido [Object.getOwnPropertySymbols(obj)](mdn:js/Object/getOwnPropertySymbols)que nos permite obter todos os symbols. Também há um método chamado [Reflect.ownKeys(obj)](mdn:js/Reflect/ownKeys)que retorna _todas_ as chaves de um objeto, incluindo as simbólicas. No entanto, a maioria das bibliotecas, funções embutidas e construções de syntaxe não utilizam esses métodos.
0 commit comments