Skip to content

Commit 6275846

Browse files
committed
Merge branch 'symbol' into update-symbol
2 parents 9269d5b + a9f2283 commit 6275846

File tree

1 file changed

+102
-103
lines changed

1 file changed

+102
-103
lines changed
Lines changed: 102 additions & 103 deletions
Original file line numberDiff line numberDiff line change
@@ -1,153 +1,151 @@
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, não booleanos, apenas *strings* (cadeias-de-carateres) 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, vimos apenas utilizando *strings*. Então, vejamos os benefícios que *symbols* nos dão.
77

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

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

12-
A value of this type can be created using `Symbol()`:
12+
Um valor deste tipo, pode ser criado utilizando `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+
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):
2020

2121
```js run
22-
// id is a symbol with the description "id"
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, sem efeito algum.
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 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.
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+
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.
4343
44-
For instance, this `alert` will show an error:
44+
Por exemplo, este `alert` exibirá um erro:
4545
4646
```js run
4747
let id = Symbol("id");
4848
*!*
4949
alert(id); // TypeError: Cannot convert a Symbol value to a string
50+
// TypeError: Não é possível converter um valor 'Symbol' para uma 'string'
5051
*/!*
5152
```
5253
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.
5455
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:
5657
```js run
5758
let id = Symbol("id");
5859
*!*
59-
alert(id.toString()); // Symbol(id), now it works
60+
alert(id.toString()); // 'Symbol(id)', agora funciona
6061
*/!*
6162
```
6263
63-
Or get `symbol.description` property to show the description only:
64+
Ou empregar a propriedade `symbol.description` para apenas mostrar a sua descrição:
6465
```js run
6566
let id = Symbol("id");
6667
*!*
67-
alert(id.description); // id
68+
alert(id.description); // 'id'
6869
*/!*
6970
```
7071
7172
````
7273

73-
## "Hidden" properties
74+
## Propriedades "Ocultas"
7475

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

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

82-
Let's use a symbol key for it:
83-
>>>>>>> 852ee189170d9022f67ab6d387aeae76810b5923
80+
Vamos utilizar uma chave *symbol* para isso:
8481

8582
```js run
86-
let user = { // belongs to another code
83+
let user = { // pertence a outro código
8784
name: "John"
8885
};
8986

9087
let id = Symbol("id");
9188

9289
user[id] = 1;
9390

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)
9592
```
9693

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

99-
Let's make the example a bit deeper to see that.
96+
Façamos um exemplo um pouco mais aprofundado para o vermos.
10097

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

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

105102
```js
106103
// ...
107104
let id = Symbol("id");
108105

109-
user[id] = "Their id value";
106+
user[id] = "O seu 'id' é válido";
110107
```
111108

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

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

116113
```js run
117114
let user = { name: "John" };
118115

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

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

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!
126123
```
127124

128-
### Symbols in a literal
125+
### Símbolos num literal
129126

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

132-
Like this:
129+
Desta forma:
133130

134131
```js
135132
let id = Symbol("id");
136133

137134
let user = {
138135
name: "John",
139136
*!*
140-
[id]: 123 // not "id: 123"
137+
[id]: 123 // não "id: 123"
141138
*/!*
142139
};
143140
```
144-
That's because we need the value from the variable `id` as the key, not the string "id".
145141

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".
147143

148-
Symbolic properties do not participate in `for..in` loop.
144+
### Símbolos são saltados num *for..in*
149145

150-
For instance:
146+
Propriedades simbólicas não são consideradas num laço (*loop*) `for..in`.
147+
148+
Por exemplo:
151149

152150
```js run
153151
let id = Symbol("id");
@@ -158,16 +156,16 @@ let user = {
158156
};
159157

160158
*!*
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)
162160
*/!*
163161

164-
// the direct access by the symbol works
162+
// o acesso direto por meio do símbolo funciona
165163
alert( "Direct: " + user[id] );
166164
```
167165

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

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

172170
```js run
173171
let id = Symbol("id");
@@ -180,113 +178,114 @@ let clone = Object.assign({}, user);
180178
alert( clone[id] ); // 123
181179
```
182180

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

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*.
187185
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:
189187
190188
```js run
191189
let obj = {
192-
0: "test" // same as "0": "test"
190+
0: "test" // o mesmo que "0": "test"
193191
};
194192
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")
196194
alert( obj["0"] ); // test
197-
alert( obj[0] ); // test (same property)
195+
alert( obj[0] ); // test (a mesma propriedade)
198196
```
199197
````
200198

201-
## Global symbols
199+
## Símbolos globais
202200

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

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

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

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

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

213-
For instance:
211+
Por exemplo:
214212

215213
```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
218216

219-
// read it again
217+
// volta a ler
220218
let idAgain = Symbol.for("id");
221219

222-
// the same symbol
223-
alert( id === idAgain ); // true
220+
// é o mesmo símbolo
221+
alert( id === idAgain ); // true (verdadeiro)
224222
```
225223

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

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.
230228
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.
232230
```
233231

234232
### Symbol.keyFor
235233

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

238-
For instance:
236+
Por exemplo:
239237

240238
```js run
241239
let sym = Symbol.for("name");
242240
let sym2 = Symbol.for("id");
243241

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'
247245
```
248246

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

251-
For instance:
249+
Por exemplo:
252250

253251
```js run
254-
alert( Symbol.keyFor(Symbol.for("name")) ); // name, global symbol
252+
alert( Symbol.keyFor(Symbol.for("name")) ); // 'name', símbolo global
255253

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
257255
```
258256

259-
## System symbols
257+
## Símbolos do sistema
260258

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

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

265263
- `Symbol.hasInstance`
266264
- `Symbol.isConcatSpreadable`
267265
- `Symbol.iterator`
268266
- `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.
270270

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

273-
Other symbols will also become familiar when we study the corresponding language features.
273+
## Sumário
274274

275-
## Summary
275+
`Symbol`, é um tipo primitivo para identicadores únicos.
276276

277-
`Symbol` is a primitive type for unique identifiers.
277+
Símbolos são criados pela chamada a `Symbol()`, com uma descrição opcional.
278278

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

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

283-
Symbols have two main use cases:
283+
1. "Ocultação" de propriedades de objetos.
284284

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

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

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

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

Comments
 (0)