Skip to content

Commit afbe486

Browse files
authored
Update article.md
1 parent 13f68d6 commit afbe486

File tree

1 file changed

+101
-96
lines changed

1 file changed

+101
-96
lines changed
Lines changed: 101 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -1,149 +1,149 @@
11

2-
# Symbol type
2+
# O tipo Symbol
33

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

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

8-
## Symbols
8+
## Símbolos
99

10-
A "symbol" represents a unique identifier.
10+
Um "símbolo" representa um identificador único .
1111

12-
A value of this type can be created using `Symbol()`:
12+
Um valor deste tipo pode ser criado usando `Symbol()`:
1313

1414
```js
15-
// id is a new symbol
15+
// 'id' é um novo símbolo
1616
let id = Symbol();
1717
```
1818

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

21-
```js
22-
// id is a symbol with the description "id"
21+
```js run
22+
// 'id' é um símbolo com a descrição "id"
2323
let id = Symbol("id");
2424
```
2525

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

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

3030
```js run
3131
let id1 = Symbol("id");
3232
let id2 = Symbol("id");
3333

3434
*!*
35-
alert(id1 == id2); // false
35+
alert(id1 == id2); // false (falso)
3636
*/!*
3737
```
3838

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

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.
4343
44-
For instance, this `alert` will show an error:
44+
Por exemplo, este `alert` irá mostrar um erro:
4545
4646
```js run
4747
let id = Symbol("id");
4848
*!*
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')
5050
*/!*
5151
```
5252
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.
5454
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:
5656
```js run
5757
let id = Symbol("id");
5858
*!*
59-
alert(id.toString()); // Symbol(id), now it works
59+
alert(id.toString()); // 'Symbol(id)', agora funciona
6060
*/!*
6161
```
6262
63-
Or get `symbol.description` property to show the description only:
63+
Ou usar a propriedade `symbol.description` para mostrar apenas a sua descrição:
6464
```js run
6565
let id = Symbol("id");
6666
*!*
67-
alert(id.description); // id
67+
alert(id.description); // 'id'
6868
*/!*
6969
```
7070
7171
````
7272

73-
## "Hidden" properties
73+
## Propriedades "Ocultas"
7474

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

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

79-
Let's use a symbol key for it:
79+
Vamos utilizar uma chave *symbol* para isso:
8080

8181
```js run
82-
let user = { // belongs to another code
82+
let user = { // pertence a outro código
8383
name: "John"
8484
};
8585

8686
let id = Symbol("id");
8787

8888
user[id] = 1;
8989

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)
9191
```
9292

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

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

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

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

101101
```js
102102
// ...
103103
let id = Symbol("id");
104104

105-
user[id] = "Their id value";
105+
user[id] = "O valor 'id' dos outros";
106106
```
107107

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

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

112112
```js run
113113
let user = { name: "John" };
114114

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'";
117117

118-
// ...Another script also wants "id" for its purposes...
118+
// ...Um outro script também quer "id" para os seus fins...
119119

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!
122122
```
123123

124-
### Symbols in an object literal
124+
### Símbolos num objeto literal
125125

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

128-
Like this:
128+
Desta forma:
129129

130130
```js
131131
let id = Symbol("id");
132132

133133
let user = {
134134
name: "John",
135135
*!*
136-
[id]: 123 // not "id": 123
136+
[id]: 123 // não "id": 123
137137
*/!*
138138
};
139139
```
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".
141141

142-
### Symbols are skipped by for..in
142+
### Símbolos são saltados num *for..in*
143143

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

146-
For instance:
146+
Por exemplo:
147147

148148
```js run
149149
let id = Symbol("id");
@@ -154,16 +154,16 @@ let user = {
154154
};
155155

156156
*!*
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)
158158
*/!*
159159

160-
// the direct access by the symbol works
160+
// o acesso direto por meio do símbolo funciona
161161
alert( "Direct: " + user[id] );
162162
```
163163

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

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*:
167167

168168
```js run
169169
let id = Symbol("id");
@@ -176,97 +176,102 @@ let clone = Object.assign({}, user);
176176
alert( clone[id] ); // 123
177177
```
178178

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

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
184182

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

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

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

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

193-
For instance:
191+
Por exemplo:
194192

195193
```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
198196

199-
// read it again
197+
// volta a ler (talvez a partir de outra secção no código)
200198
let idAgain = Symbol.for("id");
201199

202-
// the same symbol
203-
alert( id === idAgain ); // true
200+
// é o mesmo símbolo
201+
alert( id === idAgain ); // true (verdadeiro)
204202
```
205203

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

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.
210208
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.
212210
```
213211

214212
### Symbol.keyFor
215213

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

218-
For instance:
216+
Por exemplo:
219217

220218
```js run
219+
// obtenha o símbolo a partir do nome
221220
let sym = Symbol.for("name");
222221
let sym2 = Symbol.for("id");
223222

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'
227226
```
228227

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

231-
For instance:
230+
Deste modo, todos os símbolos têm uma propriedade `description`.
231+
232+
Por exemplo:
232233

233234
```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
235240

236-
alert( Symbol.keyFor(Symbol("name2")) ); // undefined, the argument isn't a global symbol
241+
alert( localSymbol.description ); // 'name'
237242
```
238243

239-
## System symbols
244+
## Símbolos do sistema
240245

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

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

245250
- `Symbol.hasInstance`
246251
- `Symbol.isConcatSpreadable`
247252
- `Symbol.iterator`
248253
- `Symbol.toPrimitive`
249-
- ...and so on.
254+
- ... e assim por diante.
250255

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

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

255-
## Summary
260+
## Resumo
256261

257-
`Symbol` is a primitive type for unique identifiers.
262+
`Symbol`, é um tipo primitivo para identificadores únicos.
258263

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

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

263-
Symbols have two main use cases:
268+
Símbolos têm dois principais casos práticos:
264269

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

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

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

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

Comments
 (0)