diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:41:45 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:41:45 -0500 |
commit | 1109132f09d75da9a28b649c7677bb6ce07c40c0 (patch) | |
tree | 0dd8b084480983cf9f9680e8aedb92782a921b13 /files/he/web/javascript/reference/global_objects/object/assign/index.html | |
parent | 4b1a9203c547c019fc5398082ae19a3f3d4c3efe (diff) | |
download | translated-content-1109132f09d75da9a28b649c7677bb6ce07c40c0.tar.gz translated-content-1109132f09d75da9a28b649c7677bb6ce07c40c0.tar.bz2 translated-content-1109132f09d75da9a28b649c7677bb6ce07c40c0.zip |
initial commit
Diffstat (limited to 'files/he/web/javascript/reference/global_objects/object/assign/index.html')
-rw-r--r-- | files/he/web/javascript/reference/global_objects/object/assign/index.html | 272 |
1 files changed, 272 insertions, 0 deletions
diff --git a/files/he/web/javascript/reference/global_objects/object/assign/index.html b/files/he/web/javascript/reference/global_objects/object/assign/index.html new file mode 100644 index 0000000000..72d2b16579 --- /dev/null +++ b/files/he/web/javascript/reference/global_objects/object/assign/index.html @@ -0,0 +1,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 < arguments.length; index++) { + var nextSource = arguments[index]; + + if (nextSource !== null && 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 => { + let descriptors = Object.keys(source).reduce((descriptors, key) => { + descriptors[key] = Object.getOwnPropertyDescriptor(source, key); + return descriptors; + }, {}); + + // By default, Object.assign copies enumerable Symbols, too + Object.getOwnPropertySymbols(source).forEach(sym => { + 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> |