Skip to content

Commit fba575b

Browse files
authored
Merge pull request #182 from pasor1/article/02-object-copy
Object references and copying
2 parents f17f17e + e94e662 commit fba575b

File tree

1 file changed

+81
-77
lines changed

1 file changed

+81
-77
lines changed
Lines changed: 81 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -1,116 +1,118 @@
1-
# Object references and copying
1+
# Oggetti: riferimento e copia
22

3-
One of the fundamental differences of objects versus primitives is that objects are stored and copied "by reference", whereas primitive values: strings, numbers, booleans, etc -- are always copied "as a whole value".
3+
Una delle maggiori differenze tra oggetti e primitivi è che gli oggetti vengono memorizzati e copiati "per riferimento", mentre i primitivi (stringhe, numeri, booleani, ecc...) vengono sempre copiati "per valore".
44

5-
That's easy to understand if we look a bit under the hood of what happens when we copy a value.
5+
Questa differenza è facile da comprendere se andiamo a guardare il comportamento del linguaggio quando copiamo un valore.
66

7-
Let's start with a primitive, such as a string.
7+
Partiamo con un primitivo, ad esempio una stringa.
88

9-
Here we put a copy of `message` into `phrase`:
9+
Qui facciamo una copia di `message` in `phrase`:
1010

1111
```js
1212
let message = "Hello!";
1313
let phrase = message;
1414
```
1515

16-
As a result we have two independent variables, each one storing the string `"Hello!"`.
16+
Come risultato otteniamo due variabili distinte, ognuna delle quali contiene la stringa `"Hello!"`.
1717

1818
![](variable-copy-value.svg)
1919

20-
Quite an obvious result, right?
20+
E' un risultato abbastanza ovvio, giusto?
2121

22-
Objects are not like that.
22+
Gli oggetti non funzionano allo stesso modo.
2323

24-
**A variable assigned to an object stores not the object itself, but its "address in memory" -- in other words "a reference" to it.**
24+
**Una variabile assegnata ad un oggetto non contiene l'oggetto in sé, ma il suo "indirizzo in memoria" -- in altre parole "un riferimento" all'oggetto.**
2525

26-
Let's look at an example of such a variable:
26+
Diamo un'occhiata a un esempio di tale variabile:
2727

2828
```js
2929
let user = {
3030
name: "John"
3131
};
3232
```
3333

34-
And here's how it's actually stored in memory:
34+
Ed ecco come viene effettivamente archiviata in memoria:
3535

3636
![](variable-contains-reference.svg)
3737

38-
The object is stored somewhere in memory (at the right of the picture), while the `user` variable (at the left) has a "reference" to it.
38+
L'oggetto è archiviato da qualche parte nella memoria (a destra nell'immagine), mentre la variabile `user` (a sinistra) contiene il "riferimento" ad esso.
3939

40-
We may think of an object variable, such as `user`, as like a sheet of paper with the address of the object on it.
40+
Potremmo immaginare la "variabile oggetto" `user`, come un foglio di carta con scritto l'indirizzo dell'oggetto.
4141

42-
When we perform actions with the object, e.g. take a property `user.name`, the JavaScript engine looks at what's at that address and performs the operation on the actual object.
42+
Quando eseguiamo azioni con l'oggetto, ad es. leggere una proprietà `user.name`, il motore JavaScript guarda cosa c'è a quell'indirizzo ed esegue l'operazione sull'oggetto reale.
4343

44-
Now here's why it's important.
44+
Ecco perché è così importante.
4545

46-
**When an object variable is copied, the reference is copied, but the object itself is not duplicated.**
46+
**Quando una "variabile oggetto" viene copiata, in realtà viene copiato il riferimento, ma l'oggetto in sé non viene duplicato.**
4747

48-
For instance:
48+
Esempio:
4949

5050
```js no-beautify
5151
let user = { name: "John" };
5252

53-
let admin = user; // copy the reference
53+
let admin = user; // copia il riferimento
5454
```
5555

56-
Now we have two variables, each storing a reference to the same object:
56+
Ora abbiamo due variabili, entrambe contengono il riferimento allo stesso oggetto:
5757

5858
![](variable-copy-reference.svg)
5959

60-
As you can see, there's still one object, but now with two variables that reference it.
60+
Come puoi vedere, l'oggetto è uno solo, ma ora con due variabili che si riferiscono ad esso.
6161

62-
We can use either variable to access the object and modify its contents:
62+
Possiamo usare entrambe le variabili per accedere all'oggetto e modificarne il contenuto:
6363

6464
```js run
6565
let user = { name: 'John' };
6666

6767
let admin = user;
6868

6969
*!*
70-
admin.name = 'Pete'; // changed by the "admin" reference
70+
admin.name = 'Pete'; // modificato dal riferimento in "admin"
7171
*/!*
7272

73-
alert(*!*user.name*/!*); // 'Pete', changes are seen from the "user" reference
73+
alert(*!*user.name*/!*); // 'Pete', le modifiche sono visibili dal riferimento in "user"
7474
```
7575
76-
It's as if we had a cabinet with two keys and used one of them (`admin`) to get into it and make changes. Then, if we later use another key (`user`), we are still opening the same cabinet and can access the changed contents.
76+
E' come se avessimo un armadietto con due chiavi e ne usassimo una (`admin`) per aprirlo ed apportare delle modiche al contenuto. Quindi, successivamente, potremmo aprire lo stesso armadietto con un'altra chiave (`user`) ed accedere al contenuto modificato.
7777
78-
## Comparison by reference
78+
## Confronto per riferimento
7979
80-
Two objects are equal only if they are the same object.
80+
Due oggetti sono uguali solo se sono lo stesso oggetto. Suona un po' strano, ma ora chiariremo.
8181
82-
For instance, here `a` and `b` reference the same object, thus they are equal:
82+
Qui `a` e `b` si riferiscono allo stesso oggetto, quindi sono uguali:
8383
8484
```js run
8585
let a = {};
86-
let b = a; // copy the reference
86+
let b = a; // copia il riferimento
8787

88-
alert( a == b ); // true, both variables reference the same object
88+
alert( a == b ); // true, entrambe le variabili si riferiscono allo stesso oggetto
8989
alert( a === b ); // true
9090
```
9191
92-
And here two independent objects are not equal, even though they look alike (both are empty):
92+
Qui, invece, due oggetti identici (entrambi vuoti), ma indipendenti, non soddisfano l'uguaglianza:
93+
9394
9495
```js run
9596
let a = {};
96-
let b = {}; // two independent objects
97+
let b = {}; // due oggetti indipendenti
9798

9899
alert( a == b ); // false
99100
```
100101
101-
For comparisons like `obj1 > obj2` or for a comparison against a primitive `obj == 5`, objects are converted to primitives. We'll study how object conversions work very soon, but to tell the truth, such comparisons are needed very rarely -- usually they appear as a result of a programming mistake.
102+
Per confronti tra oggetti (Es. `obj1 > obj2`) o con primitivi (Es. `obj == 5`), gli oggetti vengono convertiti in primitivi. Vedremo molto presto come avviene questa conversione, anche se, a dire il vero, questo tipo di confronto è molto raro e generalmente è il risultato di un errore di programmazione.
102103
103-
## Cloning and merging, Object.assign
104+
## Clonazione e unione, Object.assign
104105
105-
So, copying an object variable creates one more reference to the same object.
106+
Come abbiamo detto, copiare una "variabile oggetto" crea un ulteriore riferimento allo stesso oggetto.
106107
107-
But what if we need to duplicate an object? Create an independent copy, a clone?
108+
Quindi, come possiamo fare se abbiamo bisogno di duplicare un oggetto? Creare una copia indipendente, un clone?
108109
109-
That's also doable, but a little bit more difficult, because there's no built-in method for that in JavaScript. But there is rarely a need -- copying by reference is good most of the time.
110+
Anche questo è fattibile, ma con un po' di difficoltà visto che JavaScript non ha alcun metodo integrato per farlo. In realtà non è un'operazione frequente, il più delle volte la copia per riferimento è adatta alla situazione.
110111
111-
But if we really want that, then we need to create a new object and replicate the structure of the existing one by iterating over its properties and copying them on the primitive level.
112+
Ma se proprio ne abbiamo bisogno, allora dobbiamo creare un nuovo oggetto e replicare la struttura di quello esistente iterando le sue proprietà
113+
e copiandole a livello primitivo.
112114
113-
Like this:
115+
Così:
114116
115117
```js run
116118
let user = {
@@ -119,59 +121,60 @@ let user = {
119121
};
120122

121123
*!*
122-
let clone = {}; // the new empty object
124+
let clone = {}; // il nuovo oggetto vuoto
123125

124-
// let's copy all user properties into it
126+
// copiamo nella variabile clone tutte le proprietà di user
125127
for (let key in user) {
126128
clone[key] = user[key];
127129
}
128130
*/!*
129131

130-
// now clone is a fully independent object with the same content
131-
clone.name = "Pete"; // changed the data in it
132+
// ora clone è un oggetto completamente indipendente ma con lo stesso contenuto di user
133+
clone.name = "Pete"; // cambiamo la proprietà name
132134

133-
alert( user.name ); // still John in the original object
135+
alert( user.name ); // nell'oggetto originale è rimasto "John"
134136
```
135137
136-
Also we can use the method [Object.assign](mdn:js/Object/assign) for that.
138+
Possiamo anche usare il metodo [Object.assign](mdn:js/Object/assign) .
137139
138-
The syntax is:
140+
La sintassi è:
139141
140142
```js
141143
Object.assign(dest, [src1, src2, src3...])
142144
```
143145
144-
- The first argument `dest` is a target object.
145-
- Further arguments `src1, ..., srcN` (can be as many as needed) are source objects.
146-
- It copies the properties of all source objects `src1, ..., srcN` into the target `dest`. In other words, properties of all arguments starting from the second are copied into the first object.
147-
- The call returns `dest`.
146+
- Il primo argomento `dest` è l'oggetto di destinazione.
147+
- Gli argomenti successivi `src1, ..., srcN` (possono essere quanti vogliamo) sono gli oggetti da copiare.
148+
- Il metodo copia tutte le proprietà degli oggetti `src1, ..., srcN` in quello di destinazione `dest`.
149+
- Viene restituito l'oggetto `dest`.
150+
151+
Per fare un esempio, possiamo unire diversi oggetti in uno solo:
148152
149-
For instance, we can use it to merge several objects into one:
150153
```js
151154
let user = { name: "John" };
152155

153156
let permissions1 = { canView: true };
154157
let permissions2 = { canEdit: true };
155158

156159
*!*
157-
// copies all properties from permissions1 and permissions2 into user
160+
// copia tutte le proprietà da permissions1 e permissions2 in user
158161
Object.assign(user, permissions1, permissions2);
159162
*/!*
160163

161-
// now user = { name: "John", canView: true, canEdit: true }
164+
// ora user = { name: "John", canView: true, canEdit: true }
162165
```
163166
164-
If the copied property name already exists, it gets overwritten:
167+
Se una delle proprietà copiate è già presente nell'oggetto di destinazione, verrà sovrascritta.
165168
166169
```js run
167170
let user = { name: "John" };
168171

169172
Object.assign(user, { name: "Pete" });
170173

171-
alert(user.name); // now user = { name: "Pete" }
174+
alert(user.name); // ora user = { name: "Pete" }
172175
```
173176
174-
We also can use `Object.assign` to replace `for..in` loop for simple cloning:
177+
Possiamo anche usare `Object.assign` per sostituire il ciclo `for..in` nella clonazione semplice:
175178
176179
```js
177180
let user = {
@@ -184,13 +187,14 @@ let clone = Object.assign({}, user);
184187
*/!*
185188
```
186189
187-
It copies all properties of `user` into the empty object and returns it.
190+
Vengono copiate tutte le proprietà di `user` nell'oggetto vuoto, il quale, poi, viene restituito.
191+
192+
## Clonazione nidificata
188193
189-
## Nested cloning
194+
Finora abbiamo assunto che le proprietà di `user` fossero primitive. Ma le proprietà possono anche essere riferimenti ad altri oggetti. Come si fa in questo caso?
190195
191-
Until now we assumed that all properties of `user` are primitive. But properties can be references to other objects. What to do with them?
196+
Così:
192197
193-
Like this:
194198
```js run
195199
let user = {
196200
name: "John",
@@ -203,9 +207,9 @@ let user = {
203207
alert( user.sizes.height ); // 182
204208
```
205209
206-
Now it's not enough to copy `clone.sizes = user.sizes`, because the `user.sizes` is an object, it will be copied by reference. So `clone` and `user` will share the same sizes:
210+
In questo caso non è sufficiente copiare `clone.sizes = user.sizes`. Siccome `user.sizes` è un oggetto, verrà copiato per riferimento. Quindi `clone` e `user` condivideranno lo stesso oggetto "sizes".
207211
208-
Like this:
212+
Vediamo un esempio:
209213
210214
```js run
211215
let user = {
@@ -218,21 +222,21 @@ let user = {
218222

219223
let clone = Object.assign({}, user);
220224

221-
alert( user.sizes === clone.sizes ); // true, same object
225+
alert( user.sizes === clone.sizes ); // true, è lo stesso oggetto
222226

223-
// user and clone share sizes
224-
user.sizes.width++; // change a property from one place
225-
alert(clone.sizes.width); // 51, see the result from the other one
227+
// user e clone condividono sizes
228+
user.sizes.width++; // cambiamo una proprietà da una parte
229+
alert(clone.sizes.width); // 51, e vediamo il risultato dall'altra
226230
```
227231
228-
To fix that, we should use a cloning loop that examines each value of `user[key]` and, if it's an object, then replicate its structure as well. That is called a "deep cloning".
232+
Per risolvere questo problema, dobbiamo usare un ciclo di clonazioni che esaminerà ogni valore di `user[key]` e, nel caso sia un oggetto, replichi anche la sua struttura. Questa operazione è chiamata "deep cloning" (copia profonda).
229233
230-
We can use recursion to implement it. Or, to not reinvent the wheel, take an existing implementation, for instance [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep) from the JavaScript library [lodash](https://lodash.com).
234+
Per implementare questa funzione possiamo usare la ricorsione. Oppure, per non reinventare la ruota, possiamo usare qualcosa di già pronto, ad esempio [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep) dalla libreria JavaScript [lodash](https://lodash.com).
231235
232-
````smart header="Const objects can be modified"
233-
An important side effect of storing objects as references is that an object declared as `const` *can* be modified.
236+
````smart header="Gli oggetti dichiarati con const possono essere modificati"
237+
Un importante "side effect" della memorizzazione per riferimento è che un oggetto dichiarato con `const` *può* essere modificato.
234238

235-
For instance:
239+
Esempio:
236240

237241
```js run
238242
const user = {
@@ -246,17 +250,17 @@ user.name = "Pete"; // (*)
246250
alert(user.name); // Pete
247251
```
248252

249-
It might seem that the line `(*)` would cause an error, but it does not. The value of `user` is constant, it must always reference the same object, but properties of that object are free to change.
253+
Saremmo portati a pensare che la linea `(*)` causi un errore, ma non è così. Il valore di `user` è costante, si riferisce sempre allo stesso oggetto, ma le proprietà dell'oggetto sono libere di cambiare.
250254
251-
In other words, the `const user` gives an error only if we try to set `user=...` as a whole.
255+
In altre parole, `const user` restituisce un errore solo se se proviamo a riassegnare in toto `user=...`.
252256
253-
That said, if we really need to make constant object properties, it's also possible, but using totally different methods. We'll mention that in the chapter <info:property-descriptors>.
257+
Detto questo, se vogliamo veramente rendere invariabili le proprietà di un oggetto, possiamo farlo, ma con un metodo totalmente differente. Ne parleremo nel capitolo <info:property-descriptors>.
254258
````
255259
256-
## Summary
260+
## Riepilogo
257261
258-
Objects are assigned and copied by reference. In other words, a variable stores not the "object value", but a "reference" (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object itself.
262+
Gli oggetti sono assegnati e copiati per riferimento. In altre parole una variabile non contiene il "valore oggetto" ma un "riferimento" (indirizzo in memoria) di quel valore. Quindi copiando tale variabile o passandola come argomento di una funzione si copia quel riferimento, non l'oggetto stesso.
259263

260-
All operations via copied references (like adding/removing properties) are performed on the same single object.
264+
Tutte le operazioni su un riferimento duplicato (come aggiungere o rimuovere proprietà) hanno effetto sul medesimo oggetto.
261265

262-
To make a "real copy" (a clone) we can use `Object.assign` for the so-called "shallow copy" (nested objects are copied by reference) or a "deep cloning" function, such as [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep).
266+
Per creare una "vera copia" (clonare) effettuare una cosiddetta "shallow copy" (copia superficiale) con `Object.assign`(gli oggetti nidificati vengo copiati per riferimento), oppure un "deep cloning" (copia profonda) con funzioni tipo [_.cloneDeep(obj)](https://lodash.com/docs#cloneDeep).

0 commit comments

Comments
 (0)