You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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".
4
4
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.
6
6
7
-
Let's start with a primitive, such as a string.
7
+
Partiamo con un primitivo, ad esempio una stringa.
8
8
9
-
Here we put a copy of `message`into`phrase`:
9
+
Qui facciamo una copia di `message`in`phrase`:
10
10
11
11
```js
12
12
let message ="Hello!";
13
13
let phrase = message;
14
14
```
15
15
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!"`.
17
17
18
18

19
19
20
-
Quite an obvious result, right?
20
+
E' un risultato abbastanza ovvio, giusto?
21
21
22
-
Objects are not like that.
22
+
Gli oggetti non funzionano allo stesso modo.
23
23
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.**
25
25
26
-
Let's look at an example of such a variable:
26
+
Diamo un'occhiata a un esempio di tale variabile:
27
27
28
28
```js
29
29
let user = {
30
30
name:"John"
31
31
};
32
32
```
33
33
34
-
And here's how it's actually stored in memory:
34
+
Ed ecco come viene effettivamente archiviata in memoria:
35
35
36
36

37
37
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.
39
39
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.
41
41
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.
43
43
44
-
Now here's why it's important.
44
+
Ecco perché è così importante.
45
45
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.**
47
47
48
-
For instance:
48
+
Esempio:
49
49
50
50
```js no-beautify
51
51
let user = { name:"John" };
52
52
53
-
let admin = user; //copy the reference
53
+
let admin = user; //copia il riferimento
54
54
```
55
55
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:
57
57
58
58

59
59
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.
61
61
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:
63
63
64
64
```js run
65
65
let user = { name:'John' };
66
66
67
67
let admin = user;
68
68
69
69
*!*
70
-
admin.name='Pete'; //changed by the "admin" reference
70
+
admin.name='Pete'; //modificato dal riferimento in "admin"
71
71
*/!*
72
72
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"
74
74
```
75
75
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.
77
77
78
-
## Comparison by reference
78
+
## Confronto per riferimento
79
79
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.
81
81
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:
83
83
84
84
```js run
85
85
let a = {};
86
-
let b = a; //copy the reference
86
+
let b = a; //copia il riferimento
87
87
88
-
alert( a == b ); // true, both variables reference the same object
88
+
alert( a == b ); // true, entrambe le variabili si riferiscono allo stesso oggetto
89
89
alert( a === b ); // true
90
90
```
91
91
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
+
93
94
94
95
```js run
95
96
let a = {};
96
-
let b = {}; //two independent objects
97
+
let b = {}; //due oggetti indipendenti
97
98
98
99
alert( a == b ); // false
99
100
```
100
101
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.
102
103
103
-
## Cloning and merging, Object.assign
104
+
## Clonazione e unione, Object.assign
104
105
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.
106
107
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?
108
109
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.
110
111
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.
112
114
113
-
Like this:
115
+
Così:
114
116
115
117
```js run
116
118
let user = {
@@ -119,59 +121,60 @@ let user = {
119
121
};
120
122
121
123
*!*
122
-
let clone = {}; //the new empty object
124
+
let clone = {}; //il nuovo oggetto vuoto
123
125
124
-
//let's copy all user properties into it
126
+
//copiamo nella variabile clone tutte le proprietà di user
125
127
for (let key in user) {
126
128
clone[key] = user[key];
127
129
}
128
130
*/!*
129
131
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
132
134
133
-
alert( user.name ); //still John in the original object
135
+
alert( user.name ); //nell'oggetto originale è rimasto "John"
134
136
```
135
137
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) .
137
139
138
-
The syntax is:
140
+
La sintassi è:
139
141
140
142
```js
141
143
Object.assign(dest, [src1, src2, src3...])
142
144
```
143
145
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:
148
152
149
-
For instance, we can use it to merge several objects into one:
150
153
```js
151
154
let user = { name:"John" };
152
155
153
156
let permissions1 = { canView:true };
154
157
let permissions2 = { canEdit:true };
155
158
156
159
*!*
157
-
//copies all properties from permissions1 and permissions2 into user
160
+
//copia tutte le proprietà da permissions1 e permissions2 in user
If the copied property name already exists, it gets overwritten:
167
+
Se una delle proprietà copiate è già presente nell'oggetto di destinazione, verrà sovrascritta.
165
168
166
169
```js run
167
170
let user = { name:"John" };
168
171
169
172
Object.assign(user, { name:"Pete" });
170
173
171
-
alert(user.name); //now user = { name: "Pete" }
174
+
alert(user.name); //ora user = { name: "Pete" }
172
175
```
173
176
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:
175
178
176
179
```js
177
180
let user = {
@@ -184,13 +187,14 @@ let clone = Object.assign({}, user);
184
187
*/!*
185
188
```
186
189
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
188
193
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?
190
195
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ì:
192
197
193
-
Like this:
194
198
```js run
195
199
let user = {
196
200
name:"John",
@@ -203,9 +207,9 @@ let user = {
203
207
alert( user.sizes.height ); // 182
204
208
```
205
209
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".
207
211
208
-
Like this:
212
+
Vediamo un esempio:
209
213
210
214
```js run
211
215
let user = {
@@ -218,21 +222,21 @@ let user = {
218
222
219
223
let clone =Object.assign({}, user);
220
224
221
-
alert( user.sizes===clone.sizes ); // true, same object
225
+
alert( user.sizes===clone.sizes ); // true, è lo stesso oggetto
222
226
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
226
230
```
227
231
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).
229
233
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).
231
235
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* bemodified.
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ò* esseremodificato.
234
238
235
-
For instance:
239
+
Esempio:
236
240
237
241
```js run
238
242
const user = {
@@ -246,17 +250,17 @@ user.name = "Pete"; // (*)
246
250
alert(user.name); // Pete
247
251
```
248
252
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.
250
254
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=...`.
252
256
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>.
254
258
````
255
259
256
-
## Summary
260
+
## Riepilogo
257
261
258
-
Objects are assigned and copied by reference. Inother words, a variable stores not the "object value", but a "reference" (addressinmemory) 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.
259
263
260
-
All operations via copied references (likeadding/removingproperties) 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.
261
265
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