Skip to content

Commit 57f53a2

Browse files
update symbol type
Symbol type
2 parents 4053822 + b9d9021 commit 57f53a2

File tree

1 file changed

+100
-100
lines changed

1 file changed

+100
-100
lines changed
Lines changed: 100 additions & 100 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,36 @@
1+
# O tipo Symbol
12

2-
# Symbol type
3+
Por especificação, apenas dois tipos primitivos podem ser utilizados como chaves de propriedades de objetos:
34

4-
By specification, only two primitive types may serve as object property keys:
5+
- o tipo string, ou
6+
- o tipo symbol.
57

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"]`
89

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

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

1514
## Symbols
1615

17-
A "symbol" represents a unique identifier.
16+
Um "symbol" representa um identificador único.
1817

19-
A value of this type can be created using `Symbol()`:
18+
Um valor desse tipo pode ser criado usando `Symbol()`:
2019

2120
```js
2221
let id = Symbol();
2322
```
2423

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:
2625

2726
```js
28-
// id is a symbol with the description "id"
27+
// id é um symbol com a descrição "id"
2928
let id = Symbol("id");
3029
```
3130

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

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:
3534

3635
```js run
3736
let id1 = Symbol("id");
@@ -42,14 +41,14 @@ alert(id1 == id2); // false
4241
*/!*
4342
```
4443

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

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

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.
5150
52-
For instance, this `alert` will show an error:
51+
Por exemplo, esse `alert` vai mostrar um erro:
5352
5453
```js run
5554
let id = Symbol("id");
@@ -58,18 +57,18 @@ alert(id); // TypeError: Cannot convert a Symbol value to a string
5857
*/!*
5958
```
6059
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.
6261
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:
6463
6564
```js run
6665
let id = Symbol("id");
6766
*!*
68-
alert(id.toString()); // Symbol(id), now it works
67+
alert(id.toString()); // Symbol(id), agora funciona
6968
*/!*
7069
```
7170
72-
Or get `symbol.description` property to show the description only:
71+
Ou podemos obter a propriedade `symbol.description` para exibir apenas a descrição:
7372
7473
```js run
7574
let id = Symbol("id");
@@ -80,34 +79,34 @@ alert(id.description); // id
8079
8180
````
8281

83-
## "Hidden" properties
84-
82+
## Propriedades "Ocultas"
8583

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

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

90-
Let's use a symbol key for it:
88+
Vamos usar uma chave do tipo symbol para isso:
9189

9290
```js run
93-
let user = { // belongs to another code
94-
name: "John"
91+
let user = {
92+
// pertence a outro código
93+
name: "John",
9594
};
9695

9796
let id = Symbol("id");
9897

9998
user[id] = 1;
10099

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
102101
```
103102

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"`?
105104

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

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

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:
111110

112111
```js
113112
// ...
@@ -116,45 +115,46 @@ let id = Symbol("id");
116115
user[id] = "Their id value";
117116
```
118117

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

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:
122121

123122
```js
124123
let user = { name: "John" };
125124

126-
// Our script uses "id" property
125+
// Nosso script usa a propriedade "id"
127126
user.id = "Our id value";
128127

129-
// ...Another script also wants "id" for its purposes...
128+
// ...Outro script também quer usar a propriedade "id" para os seus fins...
130129

131-
user.id = "Their id value"
132-
// Boom! overwritten by another script!
130+
user.id = "Their id value";
131+
// Boom! Sobrescrito por outro script!
133132
```
134133

135-
### Symbols in an object literal
134+
### Symbols em uma notação literal de objeto
136135

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

139-
Like this:
138+
Assim:
140139

141140
```js
142141
let id = Symbol("id");
143142

144143
let user = {
145144
name: "John",
146145
*!*
147-
[id]: 123 // not "id": 123
146+
[id]: 123 // não "id": 123
148147
*/!*
149148
};
150149
```
151-
That's because we need the value from the variable `id` as the key, not the string "id".
152150

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
154154

155-
Symbolic properties do not participate in `for..in` loop.
155+
Propriedades simbólicas não participam do loop `for..in`.
156156

157-
For instance:
157+
Por exemplo:
158158

159159
```js run
160160
let id = Symbol("id");
@@ -165,125 +165,125 @@ let user = {
165165
};
166166

167167
*!*
168-
for (let key in user) alert(key); // name, age (no symbols)
168+
for (let key in user) alert(key); // name, age (sem symbols)
169169
*/!*
170170

171-
// the direct access by the symbol works
171+
// o acesso direto por meio do symbol funciona
172172
alert( "Direct: " + user[id] ); // Direct: 123
173173
```
174174

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

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

179179
```js run
180180
let id = Symbol("id");
181181
let user = {
182-
[id]: 123
182+
[id]: 123,
183183
};
184184

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

187-
alert( clone[id] ); // 123
187+
alert(clone[id]); // 123
188188
```
189189

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`).
191191

192-
## Global symbols
192+
## Symbols globais
193193

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

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

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)`.
199199

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

202-
For instance:
202+
Por exemplo:
203203

204204
```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
207207

208-
// read it again (maybe from another part of the code)
208+
// lê novamente (talvez de alguma outra parte do código)
209209
let idAgain = Symbol.for("id");
210210

211-
// the same symbol
212-
alert( id === idAgain ); // true
211+
// o mesmo symbol
212+
alert(id === idAgain); // true
213213
```
214214

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

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.
219219
220-
In JavaScript, as we can see, that's true for global symbols.
220+
Em JavaScript, como podemos ver, isso é verdade para symbols globais.
221221
```
222222

223223
### Symbol.keyFor
224224

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)`:
226226

227-
For instance:
227+
Por exemplo:
228228

229229
```js run
230-
// get symbol by name
230+
// obtém o symbol pelo nome
231231
let sym = Symbol.for("name");
232232
let sym2 = Symbol.for("id");
233233

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
237237
```
238238

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`
240240

241-
That said, all symbols have the `description` property.
241+
Dito isso, todos os symbols têm a propriedade `description`
242242

243-
For instance:
243+
Por exemplo:
244244

245245
```js run
246246
let globalSymbol = Symbol.for("name");
247247
let localSymbol = Symbol("name");
248248

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
251251

252-
alert( localSymbol.description ); // name
252+
alert(localSymbol.description); // name
253253
```
254254

255-
## System symbols
255+
## Symbols do sistema
256256

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

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):
260260

261-
- `Symbol.hasInstance`
261+
- `Symbol.hasInstance`:
262262
- `Symbol.isConcatSpreadable`
263263
- `Symbol.iterator`
264264
- `Symbol.toPrimitive`
265-
- ...and so on.
265+
- ...e assim por diante.
266266

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

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

271-
## Summary
271+
## Resumo
272272

273-
`Symbol` is a primitive type for unique identifiers.
273+
`Symbol` é um tipo primitivo para identificadores ínicos.
274274

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

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

279-
Symbols have two main use cases:
279+
Symbols têm dois principais casos de uso:
280280

281-
1. "Hidden" object properties.
281+
1. Propriedades "ocultas" de objetos.
282282

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

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

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

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

Comments
 (0)