1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
|
---
title: Object.assign()
slug: Web/JavaScript/Reference/Global_Objects/Object/assign
translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign
---
<div>{{JSRef}}</div>
<h2 id="Sommario">Sommario</h2>
<p>La funzione <strong><code>Object.assign()</code></strong> copia tutte le proprietà enumerabili da uno o più oggetti di origine in un oggetto di destinazione. Restituisce l'oggetto di destinazione.</p>
<h2 id="Sintassi">Sintassi</h2>
<pre class="syntaxbox notranslate"><code>Object.assign(<var>target</var>, ...<var>sources</var>)</code></pre>
<h3 id="Parametri">Parametri</h3>
<dl>
<dt><code>target</code></dt>
<dd>L'oggetto di destinazione.</dd>
<dt><code>sources</code></dt>
<dd>Gli oggetti di origine.</dd>
</dl>
<h2 id="Descrizione">Descrizione</h2>
<p>La funzione <code>Object.assign()</code> copia soltanto le proprietà <em>enumerabili</em> appartenenti agli oggetti di origine (non quelle che fanno parte della loro catena dei prototipi) in un oggetto di destinazione. Utilizza <code>[[Get]]</code> sugli oggetti di origine e <code>[[Put]]</code> su quello di destinazione, quindi invoca <em>getter</em> e <em>setter</em>, quando presenti. Quindi <em>assegna</em> le proprietà, piuttosto che limitarsi a copiarle o a definirne di nuove. Ciò lo rende inadatto per aggiungere nuove proprietà in un prototipo se le proprietà vengono copiate da un oggetto contenente <em>getter</em> o <em>setter</em>. Per copiare le proprietà, incluso il fatto di essere enumerabili o no, in un prototipo, bisognerebbe usare {{jsxref("Object.defineProperty()")}}.</p>
<p>Vengono copiate sia le proprietà aventi come nomi delle {{jsxref("String", "stringhe")}} che dei {{jsxref("Symbol", "simboli")}}.</p>
<p>In caso di errore, per esempio se una proprietà non è sovrascrivibile, viene generato un {{jsxref("TypeError")}}, e l'oggetto di destinazione rimane invariato.</p>
<p>Notare che <code>Object.assign()</code> non genera un errore se uno dei valori di origine è {{jsxref("null")}} o {{jsxref("undefined")}}.</p>
<h2 id="Esempi">Esempi</h2>
<h3 id="Clonare_un_oggetto">Clonare un oggetto</h3>
<p>Si potrebbe pensare di clonare un oggetto semplicemente assegnandolo ad un altra variabile:</p>
<pre class="brush: js notranslate">var obj = { a: 1 };
var copia = obj;
console.log(obj, copia); // { a: 1 }, { a: 1 }
obj.a = 2;
console.log(obj, copia); // { a: 2 }, { a: 2 }
// Ma copia.a non valeva 1?</pre>
<p>Utilizzando <code>Object.assign()</code> il problema non si verifica:</p>
<pre class="brush: js notranslate">var obj = { a: 1 };
var copia = Object.assign({}, obj);
console.log(obj, copia); // { a: 1 }, { a: 1 }
obj.a = 2;
console.log(obj, copia); // { a: 2 }, { a: 1 }
</pre>
<h3 id="Unire_più_oggetti">Unire più oggetti</h3>
<pre class="brush: js notranslate">var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };
var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 }, le proprietà vengono aggiunte all'oggetto di destinazione
</pre>
<h3 id="Copiare_proprietà_aventi_come_indici_dei_simboli">Copiare proprietà aventi come indici dei simboli</h3>
<pre class="brush: js notranslate">var o1 = { a: 1 };
var o2 = { [Symbol("foo")]: 2 };
var obj = Object.assign({}, o1, o2);
console.log(obj); // { a: 1, Symbol(foo): 2 }
</pre>
<h3 id="Le_proprietà_ereditate_o_non-enumerabili_non_vengono_copiate">Le proprietà ereditate o non-enumerabili non vengono copiate</h3>
<pre class="brush: js notranslate">var obj = Object.create({ foo: 1 }, { // foo è una proprietà ereditata
bar: {
value: 2 // bar è una proprietà non-enumerabile
},
baz: {
value: 3,
enumerable: true // baz è una proprietà enumerabile
}
});
var copia = Object.assign({}, obj);
console.log(copia); // { baz: 3 }
</pre>
<h3 id="I_valori_primitivi_vengono_trasformati_in_oggetti">I valori primitivi vengono trasformati in oggetti</h3>
<pre class="brush: js notranslate">var v1 = '123';
var v2 = true;
var v3 = 10;
var v4 = Symbol("foo");
var obj = Object.assign({}, v1, null, v2, undefined, v3, v4);
// I valori primitivi vengono trasformati in oggetti, null e undefined ignorati.
// Notare che solo le stringhe hanno proprietà enumerabili
console.log(obj); // { "0": "1", "1": "2", "2": "3" }
</pre>
<h3 id="Se_viene_generata_un_eccezione_la_funzione_si_ferma">Se viene generata un eccezione, la funzione si ferma</h3>
<pre class="brush: js notranslate">var destinazione = Object.defineProperty({}, 'foo', {
value: 1,
writeable: false
}); // destinazione.foo non può essere modificata
Object.assign(destinazione, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 });
// TypeError: "foo" is read-only
// L'eccezione viene generata quando si modifica destinazione.foo
console.log(destinazione.bar); // 2, Il primo oggetto viene copiato correttamente
console.log(destinazione.foo2); // 3, La prima proprietà del secondo oggetto viene copiata correttamente
console.log(destinazione.foo); // 1, L'eccezione viene generata qui
console.log(destinazione.foo3); // undefined, la funzione ha già finto di copiare
console.log(destinazione.baz); // undefined, la funzione ha già finto di copiare
</pre>
<h3 id="Copiare_i_getter">Copiare i getter</h3>
<pre class="brush: js notranslate">var obj = {
foo: 1,
get bar() {
return 2;
}
};
var copia = Object.assign({}, obj);
console.log(copia);
// { foo: 1, bar: 2 }, non viene copiato il getter obj.bar, ma il suo valore
// Questa funzione copia mantenendo getter e setter
function myAssign(target, ...sources) {
sources.forEach(source => {
Object.defineProperties(target, Object.keys(source).reduce((descriptors, key) => {
descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
return descriptors;
}, {}));
});
return target;
}
var copia = myAssign({}, obj);
console.log(copia);
// { foo:1, get bar() { return 2 } }
</pre>
<h2 id="Polyfill">Polyfill</h2>
<p>Questo polyfill non supporta i simboli (che comunque non sono supportati da ECMAScript 5):</p>
<pre class="brush: js notranslate">if (!Object.assign) {
Object.defineProperty(Object, 'assign', {
enumerable: false,
configurable: true,
writable: true,
value: function(target, firstSource) {
'use strict';
if (target === undefined || target === null) {
throw new TypeError('Cannot convert first argument to object');
}
var to = Object(target);
for (var i = 1; i < arguments.length; i++) {
var nextSource = arguments[i];
if (nextSource === undefined || nextSource === null) {
continue;
}
nextSource = Object(nextSource);
var keysArray = Object.keys(Object(nextSource));
for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
var nextKey = keysArray[nextIndex];
var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
if (desc !== undefined && desc.enumerable) {
to[nextKey] = nextSource[nextKey];
}
}
}
return to;
}
});
}
</pre>
<h2 id="Specifiche">Specifiche</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">Specifica</th>
<th scope="col">Stato</th>
<th scope="col">Commenti</th>
</tr>
<tr>
<td>{{SpecName('ES2015', '#sec-object.assign', 'Object.assign')}}</td>
<td>{{Spec2('ES2015')}}</td>
<td>Definizione iniziale.</td>
</tr>
</tbody>
</table>
<h2 id="Compatibilità_con_i_browser">Compatibilità con i browser</h2>
<div>{{CompatibilityTable}}</div>
<div id="compat-desktop">
<table class="compat-table">
<tbody>
<tr>
<th>Funzionalità</th>
<th>Chrome</th>
<th>Edge</th>
<th>Firefox (Gecko)</th>
<th>Internet Explorer</th>
<th>Opera</th>
<th>Safari</th>
</tr>
<tr>
<td>Supporto di base</td>
<td>{{CompatChrome("45")}}</td>
<td>{{CompatVersionUnknown}}</td>
<td>{{CompatGeckoDesktop("34")}}</td>
<td>{{CompatNo}}</td>
<td>{{CompatOpera("32")}}</td>
<td>{{CompatSafari("9")}}</td>
</tr>
</tbody>
</table>
</div>
<div id="compat-mobile">
<table class="compat-table">
<tbody>
<tr>
<th><span style="font-family: open sans light,sans-serif; font-size: 16px; line-height: 16px;">Funzionalità</span></th>
<th>Android</th>
<th>Chrome for Android</th>
<th>Edge</th>
<th>Firefox Mobile (Gecko)</th>
<th>IE Mobile</th>
<th>Opera Mobile</th>
<th>Safari Mobile</th>
</tr>
<tr>
<td><span style="font-size: 12px; line-height: 18px;">Supporto di base</span></td>
<td>{{CompatNo}}</td>
<td>{{CompatChrome("45")}}</td>
<td>{{CompatVersionUnknown}}</td>
<td>{{CompatGeckoMobile("34")}}</td>
<td>{{CompatNo}}</td>
<td>{{CompatNo}}</td>
<td>{{CompatVersionUnknown}}</td>
</tr>
</tbody>
</table>
</div>
<h2 id="Vedi_anche">Vedi anche</h2>
<ul>
<li>{{jsxref("Object.defineProperties()")}}</li>
</ul>
|