aboutsummaryrefslogtreecommitdiff
path: root/files/he/web/javascript/reference/global_objects/object/assign/index.html
blob: 72d2b16579d6999fc54c2921656ce89c06c96e4a (plain)
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
269
270
271
272
---
title: Object.assign()
slug: Web/JavaScript/Reference/Global_Objects/Object/assign
translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign
---
<p>{{JSRef}}</p>

<p dir="rtl">מתודת <span class="seoSummary"><strong><code>Object.assign</code> מעתיקה אובייקט על שלל </strong>{{jsxref("Object/propertyIsEnumerable", "מאפייניו", "", 1)} {{jsxref("Object/hasOwnProperty", "הקיימים", "", 1)}} לאובייקט אחר וממזגת אותם ביחד. המתודה מחזירה את האובייקט שאליו העתקנו את התכונות החדשות. </span></p>

<div dir="rtl">תחביר</div>

<pre class="syntaxbox notranslate">Object.assign(<var>target</var>, ...<var>sources</var>)</pre>

<h3 dir="rtl" id="פרמטרים">פרמטרים</h3>

<dl>
 <dt dir="rtl"><code><var>target - אובייקט היעד</var></code></dt>
 <dd dir="rtl">אובייקט היעד- האובייקט שאליו אנחנו מעתיקים את כל המאפיינים של האובייקט המקורי, כאשר הוא מחזיר את האובייקט אחרי המיזוג.</dd>
 <dt dir="rtl"><code><var>sources - אובייקט המקור</var></code></dt>
 <dd></dd>
</dl>

<dl>
 <dd dir="rtl">אובייקט המקור - האובייקט מכיל את המאפיינים שאנחנו רוצים להעתיק לאובייקט נוסף. </dd>
</dl>

<h3 dir="rtl" id="Return_value_-_הנתון_התוצאה">Return value - הנתון התוצאה</h3>

<p dir="rtl">The target object - האובייקט שאליו העתקנו את התכונות של האובייקט המקורי.</p>

<h2 dir="rtl" id="תיאור">תיאור</h2>

<p dir="rtl">מאפיינים באובייקט היעד ישוכתבו או ידרסו ע"י המאפיינים של אובייקט המקור אם הם חולקים את אותו ה-{{jsxref("Object/keys", "key", "", 1)}}. מאפיינים חדשים שיוגדו על מאפיינים משותפים (properties) בהמשך ידרסו גם באובייקט היעד וגם באופייקט המקור.</p>

<p dir="rtl"></p>

<p>The <code>Object.assign()</code> method only copies <em>enumerable</em> and <em>own</em> properties from a source object to a target object. It uses <code>[[Get]]</code> on the source and <code>[[Set]]</code> on the target, so it will invoke <a href="/en-US/docs/Web/JavaScript/Reference/Functions/get">getters</a> and <a href="/en-US/docs/Web/JavaScript/Reference/Functions/set">setters</a>. Therefore it <em>assigns</em> properties, versus copying or defining new properties. This may make it unsuitable for merging new properties into a prototype if the merge sources contain getters.</p>

<p>For copying property definitions (including their enumerability) into prototypes, use {{jsxref("Object.getOwnPropertyDescriptor()")}} and {{jsxref("Object.defineProperty()")}} instead.</p>

<p>Both {{jsxref("String")}} and {{jsxref("Symbol")}} properties are copied.</p>

<p>In case of an error, for example if a property is non-writable, a {{jsxref("TypeError")}} is raised, and the <code><var>target</var></code> object is changed if any properties are added before the error is raised.</p>

<div class="blockIndicator note">
<p><strong>Note:</strong> <code>Object.assign()</code> does not throw on {{jsxref("null")}} or {{jsxref("undefined")}} sources.</p>
</div>

<h2 id="Polyfill">Polyfill</h2>

<p>This <a href="/en-US/docs/Glossary/Polyfill">polyfill</a> doesn't support symbol properties, since ES5 doesn't have symbols anyway:</p>

<pre class="brush: js notranslate">if (typeof Object.assign !== 'function') {
  // Must be writable: true, enumerable: false, configurable: true
  Object.defineProperty(Object, "assign", {
    value: function assign(target, varArgs) { // .length of function is 2
      'use strict';
      if (target === null || target === undefined) {
        throw new TypeError('Cannot convert undefined or null to object');
      }

      var to = Object(target);

      for (var index = 1; index &lt; arguments.length; index++) {
        var nextSource = arguments[index];

        if (nextSource !== null &amp;&amp; nextSource !== undefined) {
          for (var nextKey in nextSource) {
            // Avoid bugs when hasOwnProperty is shadowed
            if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
              to[nextKey] = nextSource[nextKey];
            }
          }
        }
      }
      return to;
    },
    writable: true,
    configurable: true
  });
}
</pre>

<h2 id="Examples">Examples</h2>

<h3 id="Cloning_an_object">Cloning an object</h3>

<pre class="brush: js notranslate">const obj = { a: 1 };
const copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }
</pre>

<h3 id="Deep_Clone" name="Deep_Clone">Warning for Deep Clone</h3>

<p>For deep cloning, we need to use alternatives, because <code>Object.assign()</code> copies property values.</p>

<p>If the source value is a reference to an object, it only copies the reference value.</p>

<pre class="brush: js notranslate">function test() {
  'use strict';

  let obj1 = { a: 0 , b: { c: 0}};
  let obj2 = Object.assign({}, obj1);
  console.log(JSON.stringify(obj2)); // { "a": 0, "b": { "c": 0}}

  obj1.a = 1;
  console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 0}}
  console.log(JSON.stringify(obj2)); // { "a": 0, "b": { "c": 0}}

  obj2.a = 2;
  console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 0}}
  console.log(JSON.stringify(obj2)); // { "a": 2, "b": { "c": 0}}

  obj2.b.c = 3;
  console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 3}}
  console.log(JSON.stringify(obj2)); // { "a": 2, "b": { "c": 3}}

  // Deep Clone
  obj1 = { a: 0 , b: { c: 0}};
  let obj3 = JSON.parse(JSON.stringify(obj1));
  obj1.a = 4;
  obj1.b.c = 4;
  console.log(JSON.stringify(obj3)); // { "a": 0, "b": { "c": 0}}
}

test();</pre>

<h3 id="Merging_objects">Merging objects</h3>

<pre class="brush: js notranslate">const o1 = { a: 1 };
const o2 = { b: 2 };
const o3 = { c: 3 };

const obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1);  // { a: 1, b: 2, c: 3 }, target object itself is changed.</pre>

<h3 id="Merging_objects_with_same_properties">Merging objects with same properties</h3>

<pre class="brush: js notranslate">const o1 = { a: 1, b: 1, c: 1 };
const o2 = { b: 2, c: 2 };
const o3 = { c: 3 };

const obj = Object.assign({}, o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }</pre>

<p>The properties are overwritten by other objects that have the same properties later in the parameters order.</p>

<h3 id="Copying_symbol-typed_properties">Copying symbol-typed properties</h3>

<pre class="brush: js notranslate">const o1 = { a: 1 };
const o2 = { [Symbol('foo')]: 2 };

const obj = Object.assign({}, o1, o2);
console.log(obj); // { a : 1, [Symbol("foo")]: 2 } (cf. bug 1207182 on Firefox)
Object.getOwnPropertySymbols(obj); // [Symbol(foo)]
</pre>

<h3 id="Properties_on_the_prototype_chain_and_non-enumerable_properties_cannot_be_copied">Properties on the prototype chain and non-enumerable properties cannot be copied</h3>

<pre class="brush: js notranslate">const obj = Object.create({ foo: 1 }, { // foo is on obj's prototype chain.
  bar: {
    value: 2  // bar is a non-enumerable property.
  },
  baz: {
    value: 3,
    enumerable: true  // baz is an own enumerable property.
  }
});

const 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 notranslate">const v1 = 'abc';
const v2 = true;
const v3 = 10;
const v4 = Symbol('foo');

const 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": "a", "1": "b", "2": "c" }
</pre>

<h3 id="Exceptions_will_interrupt_the_ongoing_copying_task">Exceptions will interrupt the ongoing copying task</h3>

<pre class="brush: js notranslate">const target = Object.defineProperty({}, 'foo', {
  value: 1,
  writable: 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 notranslate">const obj = {
  foo: 1,
  get bar() {
    return 2;
  }
};

let 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 that copies full descriptors
function completeAssign(target, ...sources) {
  sources.forEach(source =&gt; {
    let descriptors = Object.keys(source).reduce((descriptors, key) =&gt; {
      descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
      return descriptors;
    }, {});

    // By default, Object.assign copies enumerable Symbols, too
    Object.getOwnPropertySymbols(source).forEach(sym =&gt; {
      let descriptor = Object.getOwnPropertyDescriptor(source, sym);
      if (descriptor.enumerable) {
        descriptors[sym] = descriptor;
      }
    });
    Object.defineProperties(target, descriptors);
  });
  return target;
}

copy = completeAssign({}, obj);
console.log(copy);
// { foo:1, get bar() { return 2 } }
</pre>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">Specification</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-object.assign', 'Object.assign')}}</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>



<p>{{Compat("javascript.builtins.Object.assign")}}</p>

<h2 id="See_also">See also</h2>

<ul>
 <li>{{jsxref("Object.defineProperties()")}}</li>
 <li><a href="/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties">Enumerability and ownership of properties</a></li>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Spread_in_object_literals">Spread in object literals</a></li>
</ul>