Skip to content

Commit fd1becf

Browse files
authored
Merge pull request #44 from armino-dev/master
Symbol type
2 parents fec94d3 + 9a40388 commit fd1becf

File tree

1 file changed

+92
-92
lines changed

1 file changed

+92
-92
lines changed
+92-92
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,31 @@
11

2-
# Symbol type
2+
# Tipul simbol ("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+
Conform specificațiilor, cheile proprietății obiectului pot fi fie de tip șir ("string"), fie de tip simbol ("symbol"). Nu numere, nu booleene, doar șiruri sau simboluri, aceste două tipuri.
55

6-
Till now we've been using only strings. Now let's see the benefits that symbols can give us.
6+
Până acum am folosit doar șiruri. Acum să vedem ce avantaje ne oferă simbolurile.
77

8-
## Symbols
8+
## Simboluri
99

10-
A "symbol" represents a unique identifier.
10+
Un "symbol" reprezintă un identificator unic.
1111

12-
A value of this type can be created using `Symbol()`:
12+
O valoare de acest tip poate fi creată folosind `Symbol()`:
1313

1414
```js
15-
// id is a new symbol
15+
// id-ul noului simbol
1616
let id = Symbol();
1717
```
1818

19-
Upon creation, we can give symbol a description (also called a symbol name), mostly useful for debugging purposes:
19+
După creare, putem aloca o descriere simbolului (mai numită și nume de simbol), folositoare îndeosebi pentru scopuri de depanare:
2020

2121
```js run
22-
// id is a symbol with the description "id"
22+
// id este un simbol cu descrierea "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+
Simbolurile sunt garantate a fi unice. Chiar dacă creăm mai multe simboluri cu aceeași descriere, ele reprezintă valori diferite. Descrierea este doar o etichetă care nu afectează nimic.
2727

28-
For instance, here are two symbols with the same description -- they are not equal:
28+
De exemplu, mai jos sunt două simboluri cu aceeași descriere -- ele nu sunt egale:
2929

3030
```js run
3131
let id1 = Symbol("id");
@@ -36,12 +36,12 @@ alert(id1 == id2); // false
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+
Dacă sunteți familiari cu Ruby sau alt limbaj de programare ce are de asemenea orice fel de "simboluri" -- nu vă lăsați păcălit. Simbolurile JavaScript sunt diferite.
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="Simbolurile nu se auto-convertesc la un șir"
42+
Cele mai multe valori în JavaScript suportă conversie implicită la un șir. De exemplu, putem `alert`-a aproape orice valoare și va funcționa. Simbolurile sunt speciale. Ele nu se auto-convertesc.
4343
44-
For instance, this `alert` will show an error:
44+
De exemplu, următoarea instrucțiune `alert` va genera o eroare:
4545
4646
```js run
4747
let id = Symbol("id");
@@ -50,17 +50,17 @@ alert(id); // TypeError: Cannot convert a Symbol value to a string
5050
*/!*
5151
```
5252
53-
That's a "language guard" against messing up, because strings and symbols are fundamentally different and should not occasionally convert one into another.
53+
Aceasta este "protecția limbajului" ("language guard") împotriva stricăciunilor, deoarece șirurile și simbolurile sunt fundamental diferite și nu ar trebui convertite ocazional dintr-unul în altul.
5454
55-
If we really want to show a symbol, we need to explicitly call `.toString()` on it, like here:
55+
Dacă vrem neapărat să afișăm un simbol, trebuie să apelăm explicit metoda `.toString()` a acestuia, ca aici:
5656
```js run
5757
let id = Symbol("id");
5858
*!*
59-
alert(id.toString()); // Symbol(id), now it works
59+
alert(id.toString()); // Symbol(id), acum funcționează
6060
*/!*
6161
```
6262
63-
Or get `symbol.description` property to show the description only:
63+
Sau să obținem proprietatea `symbol.description` pentru a afișa numai descrierea:
6464
```js run
6565
let id = Symbol("id");
6666
*!*
@@ -70,33 +70,33 @@ alert(id.description); // id
7070
7171
````
7272

73-
## "Hidden" properties
73+
## Proprietăți "ascunse"
7474

75-
Symbols allow us to create "hidden" properties of an object, that no other part of code can occasionally access or overwrite.
75+
Simbolurile ne permit să creăm proprietăți ascunse ale unui obiect, pe care nicio bucată de cod nu le poate accesa sau rescrie accidental.
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+
De exemplu, dacă lucrăm cu obiecte `user`, ce fac parte din cod extern, am dori să le adăugăm identificatori.
7878

79-
Let's use a symbol key for it:
79+
Să folosim o cheie simbol pentru asta:
8080

8181
```js run
82-
let user = { // belongs to another code
82+
let user = { // aparține altui cod
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] ); // putem accesa informația folosind simbolul ca și cheie
9191
```
9292

93-
What's the benefit of using `Symbol("id")` over a string `"id"`?
93+
Care sunt avantajele folosirii `Symbol("id")` față de un șir `"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 occasionally, the third-party code probably won't even see it, so it's probably all right to do.
95+
Deoarece obiectele `user` aparțin altui cod, și acel cod lucrează de asemenea cu acestea, nu ar trebui să adăugăm niciun câmp la ele. Este nesigur. Însă un simbol nu poate fi accesat accidental, codul extern, probabil, nici nu-l va vedea, deci pesemne este în regulă să o facem.
9696

97-
Also, imagine that another script wants to have its own identifier inside `user`, for its own purposes. That may be another JavaScript library, so that the scripts are completely unaware of each other.
97+
De asemenea, imaginați-vă că un alt script dorește să aibă propriul său identificator în interiorul obiectului `user`, pentru propriile sale scopuri. Poate fi o altă librărie JavaScript, astfel că script-urile nu știu unul de existența celuilalt.
9898

99-
Then that script can create its own `Symbol("id")`, like this:
99+
Apoi acel script își poate crea propriul `Symbol("id")`, ca aici:
100100

101101
```js
102102
// ...
@@ -105,45 +105,45 @@ let id = Symbol("id");
105105
user[id] = "Their id value";
106106
```
107107

108-
There will be no conflict between our and their identifiers, because symbols are always different, even if they have the same name.
108+
Nu va exista niciun conflict între identificatorul nostru și al lor, deoarece simbolurile sunt întotdeauna diferite, chiar dacă au același nume.
109109

110-
...But if we used a string `"id"` instead of a symbol for the same purpose, then there *would* be a conflict:
110+
...Însă, dacă am folosi un șir `"id"` în loc de un simbol pentru același scop, atunci *va* exista un conflict:
111111

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

115-
// Our script uses "id" property
115+
// Script-ul nostru folosește proprietatea "id"
116116
user.id = "Our id value";
117117

118-
// ...Another script also wants "id" for its purposes...
118+
// ...Alt script dorește "id" pentru scopurile sale...
119119

120120
user.id = "Their id value"
121-
// Boom! overwritten by another script!
121+
// Boom! rescris de alt script!
122122
```
123123

124-
### Symbols in a literal
124+
### Simboluri într-un literal
125125

126-
If we want to use a symbol in an object literal `{...}`, we need square brackets around it.
126+
Dacă vrem să folosim un simbol într-un obiect literal `{...}`, avem nevoie de paranteze pătrate în jurul lui.
127127

128-
Like this:
128+
Ca aici:
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 // nu "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+
Asta deoarece avem nevoie de valoarea din variabila `id` ca și cheie, nu de șirul "id".
141141

142-
### Symbols are skipped by for..in
142+
### Simbolurile sunt ignorate de bucla for..in
143143

144-
Symbolic properties do not participate in `for..in` loop.
144+
Proprietățile simboluri nu participă în bucla `for..in`.
145145

146-
For instance:
146+
De exemplu:
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 (niciun simbol)
158158
*/!*
159159

160-
// the direct access by the symbol works
160+
// accesul direct către simbol funcționează
161161
alert( "Direct: " + user[id] );
162162
```
163163

164-
`Object.keys(user)` 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.
164+
`Object.keys(user)` le ignoră, de asemenea. Aceasta este o parte a principiului general "ascunderea proprietăților simbol". Dacă un alt script sau librărie iterează asupra obiectului, nu va accesa neașteptat o proprietate simbol.
165165

166-
In contrast, [Object.assign](mdn:js/Object/assign) copies both string and symbol properties:
166+
În contrast, metoda [Object.assign](mdn:js/Object/assign) copiază proprietățile de ambele tipuri, șir și simbol:
167167

168168
```js run
169169
let id = Symbol("id");
@@ -176,118 +176,118 @@ 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`).
179+
Nu este niciun paradox aici. Așa este construit. Ideea este că, atunci când clonăm un obiect sau contopim obiecte, în mod normal vrem ca *toate* proprietățile să fie copiate (incluzând simboluri precum `id`).
180180

181-
````smart header="Property keys of other types are coerced to strings"
182-
We can only use strings or symbols as keys in objects. Other types are converted to strings.
181+
````smart header="Proprietățile cheie de alte tipuri sunt forțate la șiruri"
182+
Putem folosi doar șiruri sau simboluri ca și chei în obiecte. Alte tipuri sunt convertite la șiruri.
183183
184-
For instance, a number `0` becomes a string `"0"` when used as a property key:
184+
De exemplu, un număr `0` devine un șir `"0"` când este folosit ca și proprietate cheie:
185185
186186
```js run
187187
let obj = {
188-
0: "test" // same as "0": "test"
188+
0: "test" // identic cu "0": "test"
189189
};
190190
191-
// both alerts access the same property (the number 0 is converted to string "0")
191+
// ambele alerte accesează aceeași proprietate (numărul 0 este convertit la șirul "0")
192192
alert( obj["0"] ); // test
193-
alert( obj[0] ); // test (same property)
193+
alert( obj[0] ); // test (aceeași proprietate)
194194
```
195195
````
196196

197-
## Global symbols
197+
## Simboluri globale
198198

199-
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.
199+
După cum am văzut, în mod normal toate simbolurile sunt diferite, chiar dacă au același nume. Însă câteodată dorim ca simbolurile numite identic să fie aceleași entități. De exemplu, diferite părți ale aplicației noastre doresc să acceseze simbolul `"id"` care să însemne exact aceeași proprietate.
200200

201-
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.
201+
Pentru a realiza acest lucru, există un *registru global de simboluri*. Putem crea simboluri în el și le putem accesa mai târziu, și garantează că accesări repetate după același nume returnează fix același simbol.
202202

203-
In order to read (create if absent) a symbol from the registry, use `Symbol.for(key)`.
203+
Pentru a citi (crea dacă nu există) un simbol din registru, folosiți `Symbol.for(key)`.
204204

205-
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`.
205+
Acest apel verifică registrul global, și dacă există un simbol descris ca și cheie, atunci îl returnează, în caz contrar, creează un nou simbol `Symbol(key)` și îl stochează în registru după `cheia` dată.
206206

207-
For instance:
207+
De exemplu:
208208

209209
```js run
210-
// read from the global registry
211-
let id = Symbol.for("id"); // if the symbol did not exist, it is created
210+
// citește din registrul global
211+
let id = Symbol.for("id"); // dacă simbolul nu există, îl creează
212212

213-
// read it again (maybe from another part of the code)
213+
// citește din nou (poate din altă parte a codului)
214214
let idAgain = Symbol.for("id");
215215

216-
// the same symbol
216+
// același simbol
217217
alert( id === idAgain ); // true
218218
```
219219

220-
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.
220+
Simbolurile din interiorul registrului sunt denumite *simboluri globale*. Dacă dorim un simbol pentru toată aplicația, accesibil peste tot în cod - pentru asta sunt folosite.
221221

222-
```smart header="That sounds like Ruby"
223-
In some programming languages, like Ruby, there's a single symbol per name.
222+
```smart header="Asta seamănă cu Ruby"
223+
În unele limbaje de programare, precum Ruby, există un singur simbol pentru un nume.
224224
225-
In JavaScript, as we can see, that's right for global symbols.
225+
În JavaScript, după cum putem vedea, acest fapt este adevărat pentru simbolurile globale.
226226
```
227227

228228
### Symbol.keyFor
229229

230-
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.
230+
Pentru simbolurile globale, nu numai `Symbol.for(key)` returnează un simbol după nume, dar există și un apel invers: `Symbol.keyFor(sym)`, care face reversul: returnează un nume după un simbol global.
231231

232-
For instance:
232+
De exemplu:
233233

234234
```js run
235-
// get symbol by name
235+
// accesează simbolul după nume
236236
let sym = Symbol.for("name");
237237
let sym2 = Symbol.for("id");
238238

239-
// get name by symbol
239+
// accesează numele după simbol
240240
alert( Symbol.keyFor(sym) ); // name
241241
alert( Symbol.keyFor(sym2) ); // id
242242
```
243243

244-
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`.
244+
Metoda `Symbol.keyFor` folosește intern registrul global de simboluri pentru a căuta cheia simbolului. Deci nu funcționează pentru simboluri non-globale. Dacă simbolul nu este global, nu îl va putea găsi și va returna `undefined`.
245245

246-
That said, any symbols have `description` property.
246+
Acestea fiind spuse, orice simbol poate avea proprietatea `description`.
247247

248-
For instance:
248+
De exemplu:
249249

250250
```js run
251251
let globalSymbol = Symbol.for("name");
252252
let localSymbol = Symbol("name");
253253

254-
alert( Symbol.keyFor(globalSymbol) ); // name, global symbol
255-
alert( Symbol.keyFor(localSymbol) ); // undefined, not global
254+
alert( Symbol.keyFor(globalSymbol) ); // name, simbol global
255+
alert( Symbol.keyFor(localSymbol) ); // undefined, non global
256256

257257
alert( localSymbol.description ); // name
258258
```
259259

260-
## System symbols
260+
## Simboluri sistem
261261

262-
There exist many "system" symbols that JavaScript uses internally, and we can use them to fine-tune various aspects of our objects.
262+
Există multe simboluri "sistem" pe care JavaScript le folosește intern, și pe care le putem folosi pentru a regla fin diverse aspecte ale obiectelor noastre.
263263

264-
They are listed in the specification in the [Well-known symbols](https://tc39.github.io/ecma262/#sec-well-known-symbols) table:
264+
Ele sunt listate în specificațiile din tabelul [Well-known symbols](https://tc39.github.io/ecma262/#sec-well-known-symbols):
265265

266266
- `Symbol.hasInstance`
267267
- `Symbol.isConcatSpreadable`
268268
- `Symbol.iterator`
269269
- `Symbol.toPrimitive`
270-
- ...and so on.
270+
- ...ș.a.m.d.
271271

272-
For instance, `Symbol.toPrimitive` allows us to describe object to primitive conversion. We'll see its use very soon.
272+
De exemplu, `Symbol.toPrimitive` ne permite să descriem obiectele la conversii primitive. Îi vom vedea utilizarea foarte curând.
273273

274-
Other symbols will also become familiar when we study the corresponding language features.
274+
Alte simboluri vor deveni de asemenea familiare după ce vom studia caracteristicile corespunzătoare limbajului.
275275

276-
## Summary
276+
## Rezumat
277277

278-
`Symbol` is a primitive type for unique identifiers.
278+
`Symbol` este un tip primitiv pentru identificatori unici.
279279

280-
Symbols are created with `Symbol()` call with an optional description (name).
280+
Simbolurile sunt create cu apelul `Symbol()` cu o descriere opțională (name).
281281

282-
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.
282+
Simbolurile sunt întotdeauna valori diferite, chiar dacă au același nume. Dacă vrem ca simbolurile cu același nume să fie egale, atunci trebuie să folosim registrul global: `Symbol.for(key)` returnează (creează dacă este nevoie) un simbol global cu `cheie` ca și nume. Apelări multiple ale metodei `Symbol.for` aceeași `cheie` returnează exact același simbol.
283283

284-
Symbols have two main use cases:
284+
Simbolurile au două cazuri principale de folosire:
285285

286-
1. "Hidden" object properties.
287-
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 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 occasional use or overwrite.
286+
1. Proprietăți "ascunse" ale unui obiect.
287+
Dacă vrem să adăugăm o proprietate într-un obiect care "aparține" altui script sau biblioteci, putem crea un simbol și îl putem folosi ca și proprietate cheie. O proprietate simbolică nu apare în `for..in`, motiv pentru care, nu va fi procesată accidental împreună cu alte proprietăți. De asemenea, nu va fi accesată direct, deoarece un alt script nu va avea simbolul nostru. În concluzie, proprietatea va fi protejată împotriva folosirii sau rescrierii accidentale.
288288

289-
So we can "covertly" hide something into objects that we need, but others should not see, using symbolic properties.
289+
Deci, putem ascunde "după cortină", în obiecte, ceva de care avem nevoie, dar alții nu ar trebui să vadă, folosind proprietăți simbol.
290290

291-
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.
291+
2. Există multe simboluri sistem folosite de JavaScript care sunt accesibile prin `Symbol.*`. Le putem folosi pentru a altera comportamente incluse în limbaj. De exemplu, mai târziu în tutorial vom folosi `Symbol.iterator` pentru [iterables](info:iterable), `Symbol.toPrimitive` pentru a configura [object-to-primitive conversion](info:object-toprimitive) ș.a.m.d.
292292

293-
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 functions and syntax constructs don't use these methods.
293+
Tehnic, simbolurile nu sunt 100% ascunse. Există metode ale limbajului JavaScript [Object.getOwnPropertySymbols(obj)](mdn:js/Object/getOwnPropertySymbols) care ne permit sa accesăm toate simbolurile. Mai există o metodă numită [Reflect.ownKeys(obj)](mdn:js/Reflect/ownKeys) care returnează *toate* cheile unui obiect incluzându-le și pe cele simbol. Deci ele nu sunt ascunse cu adevărat. Dar cele mai multe biblioteci, funcții incluse în limbaj și construcții de sintaxă nu folosesc aceste metode.

0 commit comments

Comments
 (0)