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
|
---
title: Object.assign()
slug: Web/JavaScript/Reference/Global_Objects/Object/assign
translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign
---
<div>{{JSRef}}</div>
<p>El mètode <strong><code>Object.assign()</code></strong> s'utilitza per copiar els valors de totes les propietats enumerables pròpies d'un o més objectes d'orígens a un objecte objectiu o destí. Retornarà l'objecte destí.</p>
<h2 id="Sintaxi">Sintaxi</h2>
<pre class="syntaxbox"><code>Object.assign(<var>target</var>, ...<var>orígens</var>)</code></pre>
<h3 id="Paràmetres">Paràmetres</h3>
<dl>
<dt><code>target</code></dt>
<dd>L'objecte destí.</dd>
<dt><code>sources</code></dt>
<dd>El(s) objecte(s) d'orígen.</dd>
</dl>
<h3 id="Valor_retornat">Valor retornat</h3>
<p>L'objecte destí (o objectiu) es retornat.</p>
<h2 id="Descripció">Descripció</h2>
<p>El mètode <code>Object.assign()</code> només copia propietats <em>enumerable</em>s i <em>pròpies</em> d'un objecte orígen a un objecte destí. S'utilitza <code>[[Get]]</code> a l'orígen i <code>[[Put]]</code> al destí, de forma que invocarà getters i setters. Per tant, <em>assigna</em> propietats en comptes de només copiar o definir noves propietats. Axò pot fer que sigui inadequat per juntar noves propietats en un prototipus si les fonts de la unió contenen getters. Per copiar definicions de la propietat, incloent la seva enumerabilitat, en prototipus s'ha de fer servir {{jsxref("Object.getOwnPropertyDescriptor()")}} i {{jsxref("Object.defineProperty()")}}.</p>
<p>Tant la propietat {{jsxref("String")}} com la propietat {{jsxref("Symbol")}} són copiades.</p>
<p>En cas d'error, per exemple si una propietat no és modificable, un {{jsxref("TypeError")}} <strong><u>s'incrementarà </u></strong>i l'objecte <code>target</code> object es mantindrà sense canvis.</p>
<p>Vegeu que <code>Object.assign()</code> does not throw on {{jsxref("null")}} or {{jsxref("undefined")}} source values.</p>
<h2 id="Exemples">Exemples</h2>
<h3 id="Clonar_un_objecte">Clonar un objecte</h3>
<pre class="brush: js">var obj = { a: 1 };
var copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }
</pre>
<h3 id="Unir_objectes">Unir objectes</h3>
<pre class="brush: js">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 }, L'objecte de destinació es canvia</pre>
<h3 id="Copiar_propietats_symbol-typed">Copiar propietats symbol-typed</h3>
<pre class="brush: js">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="Les_propietats_heretades_i_les_propietats_no_enumerables_no_es_poden_copiar">Les propietats heretades i les propietats no enumerables no es poden copiar</h3>
<pre class="brush: js">var obj = Object.create({ foo: 1 }, { // foo és una propietat heretada.
bar: {
value: 2 // bar és una propietat no enumerable.
},
baz: {
value: 3,
enumerable: true // baz is an own enumerable property.
}
});
var copy = Object.assign({}, obj);
console.log(copy); // { baz: 3 }
</pre>
<h3 id="Primitives_will_be_wrapped_to_objects">Primitives will be wrapped to objects</h3>
<pre class="brush: js">var v1 = '123';
var v2 = true;
var v3 = 10;
var v4 = Symbol('foo')
var obj = Object.assign({}, v1, null, v2, undefined, v3, v4);
// Primitives will be wrapped, null and undefined will be ignored.
// Note, only string wrappers can have own enumerable properties.
console.log(obj); // { "0": "1", "1": "2", "2": "3" }
</pre>
<h3 id="Exceptions_will_interrupt_the_ongoing_copying_task">Exceptions will interrupt the ongoing copying task</h3>
<pre class="brush: js">var target = Object.defineProperty({}, 'foo', {
value: 1,
writeable: false
}); // target.foo is a read-only property
Object.assign(target, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 });
// TypeError: "foo" is read-only
// The Exception is thrown when assigning target.foo
console.log(target.bar); // 2, the first source was copied successfully.
console.log(target.foo2); // 3, the first property of the second source was copied successfully.
console.log(target.foo); // 1, exception is thrown here.
console.log(target.foo3); // undefined, assign method has finished, foo3 will not be copied.
console.log(target.baz); // undefined, the third source will not be copied either.
</pre>
<h3 id="Copying_accessors">Copying accessors</h3>
<pre class="brush: js">var obj = {
foo: 1,
get bar() {
return 2;
}
};
var copy = Object.assign({}, obj);
console.log(copy);
// { foo: 1, bar: 2 }, the value of copy.bar is obj.bar's getter's return value.
// This is an assign function which can copy accessors.
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 copy = myAssign({}, obj);
console.log(copy);
// { foo:1, get bar() { return 2 } }
</pre>
<h2 id="Polyfill">Polyfill</h2>
<p>This polyfill doesn't support symbol properties, since ES5 doesn't have symbols anyway:</p>
<pre class="brush: js">if (!Object.assign) {
Object.defineProperty(Object, 'assign', {
enumerable: false,
configurable: true,
writable: true,
value: function(target) {
'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="Especificacions">Especificacions</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">Especificació</th>
<th scope="col">Estat</th>
<th scope="col">Comentaris</th>
</tr>
<tr>
<td>{{SpecName('ES2015', '#sec-object.assign', 'Object.assign')}}</td>
<td>{{Spec2('ES2015')}}</td>
<td>Definició inicial</td>
</tr>
</tbody>
</table>
<h2 id="Compatibilitat_de_navegadors">Compatibilitat de navegadors</h2>
<div>{{CompatibilityTable}}</div>
<div id="compat-desktop">
<table class="compat-table">
<tbody>
<tr>
<th>Caracteristica</th>
<th>Chrome</th>
<th>Firefox (Gecko)</th>
<th>Internet Explorer</th>
<th>Opera</th>
<th>Safari</th>
</tr>
<tr>
<td>Suport bàsic</td>
<td>{{CompatChrome("45")}}</td>
<td>{{CompatGeckoDesktop("34")}}</td>
<td>{{CompatNo}}</td>
<td>{{CompatNo}}</td>
<td>{{CompatNo}}</td>
</tr>
</tbody>
</table>
</div>
<div id="compat-mobile">
<table class="compat-table">
<tbody>
<tr>
<th>Característica</th>
<th>Android</th>
<th>Chrome per Android</th>
<th>Firefox Mobile (Gecko)</th>
<th>IE Mobile</th>
<th>Opera Mobile</th>
<th>Safari Mobile</th>
</tr>
<tr>
<td>Suport bàsic</td>
<td>{{CompatNo}}</td>
<td>{{CompatNo}}</td>
<td>{{CompatGeckoMobile("34")}}</td>
<td>{{CompatNo}}</td>
<td>{{CompatNo}}</td>
<td>{{CompatNo}}</td>
</tr>
</tbody>
</table>
</div>
<h2 id="Vegeu_també">Vegeu també</h2>
<ul>
<li>{{jsxref("Object.defineProperties()")}}</li>
</ul>
|