aboutsummaryrefslogtreecommitdiff
path: root/files/ko/web/javascript/reference/global_objects/object/assign/index.md
diff options
context:
space:
mode:
authoralattalatta <urty5656@gmail.com>2021-09-17 12:05:43 +0900
committerSoHyun Park <stitch.coding@gmail.com>2021-09-23 12:12:34 +0900
commit324fde1c802cc67e2bde7c365500049fc782ef1b (patch)
tree8a80b75f08c2b3df1118db6cc83421483567b1ca /files/ko/web/javascript/reference/global_objects/object/assign/index.md
parentd4b3c9fb06e79905a7d61310ff5971fe5dbe129a (diff)
downloadtranslated-content-324fde1c802cc67e2bde7c365500049fc782ef1b.tar.gz
translated-content-324fde1c802cc67e2bde7c365500049fc782ef1b.tar.bz2
translated-content-324fde1c802cc67e2bde7c365500049fc782ef1b.zip
Rename html to md
Diffstat (limited to 'files/ko/web/javascript/reference/global_objects/object/assign/index.md')
-rw-r--r--files/ko/web/javascript/reference/global_objects/object/assign/index.md267
1 files changed, 267 insertions, 0 deletions
diff --git a/files/ko/web/javascript/reference/global_objects/object/assign/index.md b/files/ko/web/javascript/reference/global_objects/object/assign/index.md
new file mode 100644
index 0000000000..31d545dd4f
--- /dev/null
+++ b/files/ko/web/javascript/reference/global_objects/object/assign/index.md
@@ -0,0 +1,267 @@
+---
+title: Object.assign()
+slug: Web/JavaScript/Reference/Global_Objects/Object/assign
+tags:
+ - ECMAScript 2015
+ - JavaScript
+ - Method
+ - Object
+ - Reference
+ - polyfill
+ - 객체
+ - 레퍼런스
+ - 메소드
+browser-compat: javascript.builtins.Object.assign
+translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign
+---
+<div>{{JSRef}}</div>
+
+<p><strong><code>Object.assign()</code> </strong>메소드는 출처 객체로부터 모든 열거할 수 있는({{jsxref("Object/propertyIsEnumerable", "enumerable", "", 1)}}) 하나 이상의 속성({{jsxref("Object/hasOwnProperty", "own properties", "", 1)}})들을 목표 객체로 복사합니다. 이는 수정된 목표 객체를 반환합니다.</p>
+
+<p>{{EmbedInteractiveExample("pages/js/object-assign.html")}}</p>
+
+<h2 id="Syntax">구문</h2>
+
+<pre class="syntaxbox">Object.assign(<var>target</var>, ...<var>sources</var>)</pre>
+
+<h3 id="Parameters">매개변수</h3>
+
+<dl>
+ <dt><code><var>target</var></code></dt>
+ <dd>목표 객체 - 출처 객체의 속성을 받아 반영된 목표 객체를 반환합니다.</dd>
+ <dt><code><var>sources</var></code></dt>
+ <dd>출처 객체(들) - 목표 객체에 반영하고자 하는 속성들을 갖고 있는 객체입니다.</dd>
+</dl>
+
+<h3 id="Return_value">반환 값</h3>
+
+<p>목표 객체</p>
+
+<h2 id="Description">설명</h2>
+
+<p>목표 객체에 동일한 {{jsxref("Object/keys", "키", "", 1)}}를 갖는 속성이 존재할 경우 그 속성 값은 출처 객체의 속성 값으로 덮어쓰여집니다. 동일하게, 앞의 출처 속성들은 뒤의 출처 속성들에게 덮어쓰여집니다.</p>
+
+<p><code>Object.assign()</code> 메소드는 출처 객체의 열거할 수 있는 속성만 목표 객체로 복사합니다. 이 메소드는 출처 객체의 <code>[[Get]]</code>, 목표 객체의 <code>[[Set]]</code> 을 사용하여 getter 와 setter 를 호출합니다. 그러므로 이는 속성을 단순히 복사하거나 새롭게 정의하는 것이 아니라 할당하는 것입니다.
+ 병합될 출처 객체들이 getter 를 포함하는 경우 프로토타입에 새로운 속성들을 병합하기에는 적절하지 않을 수 있습니다.
+</p>
+
+<p>속성의 열거성을 포함한 속성의 정의를 프로토타입으로 복사하려면 대신 {{jsxref("Object.getOwnPropertyDescriptor()")}} 와 {{jsxref("Object.defineProperty()")}} 를 사용해야합니다.</p>
+
+<p>{{jsxref("String")}} 과 {{jsxref("Symbol")}} 속성 모두가 복사됩니다.</p>
+
+<p>에러가 발생할 수 있는 상황에서는(예, 프로퍼티가 쓰기 불가인 경우), {{jsxref("TypeError")}} 가 발생하며, 에러가 발생하기 전에 속성이 추가되었다면 <code>목표</code> 객체는 변경될 수 있습니다.</p>
+
+<div class="notecard note">
+ <p><strong>Note:</strong> <code>Object.assign()</code> 메소드는
+ {{jsxref("null")}} 또는 {{jsxref("undefined")}} 출처 값에 대해서 예외를 던지지 않음을 유의하세요.</p>
+</div>
+
+<h2 id="Polyfill">폴리필</h2>
+
+<p>ES5 에는 심볼이 없기 때문에 다음 {{Glossary("Polyfill","폴리필")}} 은 심볼 속성을 지원하지 않습니다.</p>
+
+<pre class="brush: js">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) { // TypeError if undefined or null
+ 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) { // Skip over if undefined or null
+ 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">예시</h2>
+
+<h3 id="Cloning_an_object">객체 복제</h3>
+
+<pre class="brush: js">const obj = { a: 1 };
+const copy = Object.assign({}, obj);
+console.log(copy); // { a: 1 }
+</pre>
+
+<h3 id="Deep_Clone">깊은 복사에 대한 주의사항</h3>
+
+<p>깊은 복사를 위해서는, 다른 방법을 사용해야 합니다. 왜냐하면 <code>Object.assign()</code> 은 속성 값을 복사하기 때문입니다.</p>
+
+<p>만약 출처 값이 객체를 참조하고 있다면, 참조 값만 복사합니다.</p>
+
+<pre class="brush: js">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; // obj1, obj2 모두에 영향을 줌
+ console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 3}}
+ console.log(JSON.stringify(obj2)); // { a: 2, b: { c: 3}}
+
+ // 깊은 복사
+ 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">객체 병합</h3>
+
+<pre class="brush: js">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 }, 목표 객체 자체가 변경됨.</pre>
+
+<h3 id="Merging_objects_with_same_properties">같은 속성을 가진 객체 병합</h3>
+
+<pre class="brush: js">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>속성들은 매개변수 순서에서 더 뒤에 위치하고 동일한 속성을 가진 다른 객체에 의해 덮어쓰여집니다.</p>
+
+<h3 id="Copying_symbol-typed_properties">심볼형 속성 복사</h3>
+
+<pre class="brush: js">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">프로토타입 체인의 속성과 열거 할 수 없는 속성은 복사 불가</h3>
+
+<pre class="brush: js">const obj = Object.create({ foo: 1 }, { // foo 는 obj 의 프로토타입 체인에 있음.
+ bar: {
+ value: 2 // bar 는 열거할 수 없는 속성.
+ },
+ baz: {
+ value: 3,
+ enumerable: true // baz 는 열거형 속성임.
+ }
+});
+
+const copy = Object.assign({}, obj);
+console.log(copy); // { baz: 3 }
+</pre>
+
+<h3 id="Primitives_will_be_wrapped_to_objects">원시 자료형은 객체로 래핑</h3>
+
+<pre class="brush: js">var v1 = 'abc';
+var v2 = true;
+var v3 = 10;
+var v4 = Symbol('foo');
+
+var obj = Object.assign({}, v1, null, v2, undefined, v3, v4);
+// 원시 자료형은 래핑되지만, null 과 undefined 는 무시.
+// 문자열 래퍼만 자체 열거형 속성을 가짐을 유의.
+console.log(obj); // { "0": "a", "1": "b", "2": "c" }
+</pre>
+
+<h3 id="Exceptions_will_interrupt_the_ongoing_copying_task">예외에 의해 진행중인 복사 작업 중단</h3>
+
+<pre class="brush: js">var target = Object.defineProperty({}, 'foo', {
+ value: 1,
+ writable: false
+}); // target.foo 는 읽기 전용 속성
+
+Object.assign(target, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 });
+// TypeError: "foo" is read-only
+// target.foo 에 할당할 때 예외 발생
+
+console.log(target.bar); // 2, 첫 번째 출처 객체는 성공적으로 복사되었음.
+console.log(target.foo2); // 3, 두 번째 출처 객체의 첫 번째 프로퍼티도 성공적으로 복사되었음.
+console.log(target.foo); // 1, 여기에서 예외가 발생.
+console.log(target.foo3); // undefined, assign 메소드가 종료되었음, foo3 은 복사되지 않음.
+console.log(target.baz); // undefined, 세 번째 출처 객체도 복사되지 않음.
+</pre>
+
+<h3 id="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 }, copy.bar 의 값은 obj.bar 의 getter 의 반환 값임.
+
+// 모든 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;
+  }, {});
+  // 기본적으로, Object.assign 는 열거형 Symbol 도 복사함.
+  Object.getOwnPropertySymbols(source).forEach(sym =&gt; {
+  let descriptor = Object.getOwnPropertyDescriptor(source, sym);
+  if (descriptor.enumerable) {
+  descriptors[sym] = descriptor;
+  }
+  });
+ Object.defineProperties(target, descriptors);
+ });
+ return target;
+}
+
+var copy = completeAssign({}, obj);
+console.log(copy);
+// { foo:1, get bar() { return 2 } }
+</pre>
+
+<h2 id="Specifications">명세</h2>
+
+{{Specifications}}
+
+<h2 id="브라우저_호환성">브라우저 호환성</h2>
+
+<p>{{Compat}}</p>
+
+<h2 id="See_also">같이 보기</h2>
+
+<ul>
+ <li><code>Object.assign</code> 의 폴리필은 다음에서 확인할 수 있습니다. <a href="https://github.com/zloirock/core-js#ecmascript-object"><code>core-js</code></a></li>
+ <li>{{jsxref("Object.defineProperties()")}}</li>
+ <li><a href="/ko/docs/Web/JavaScript/Enumerability_and_ownership_of_properties">속성의 열거성과 소유권</a></li>
+ <li><a href="/ko/docs/Web/JavaScript/Reference/Operators/Spread_syntax#spread_in_object_literals">객체 리터럴에서의 Spread</a></li>
+</ul>