aboutsummaryrefslogtreecommitdiff
path: root/files/ko/web/javascript/reference/global_objects/object/assign
diff options
context:
space:
mode:
authorPeter Bengtsson <mail@peterbe.com>2020-12-08 14:42:17 -0500
committerPeter Bengtsson <mail@peterbe.com>2020-12-08 14:42:17 -0500
commitda78a9e329e272dedb2400b79a3bdeebff387d47 (patch)
treee6ef8aa7c43556f55ddfe031a01cf0a8fa271bfe /files/ko/web/javascript/reference/global_objects/object/assign
parent1109132f09d75da9a28b649c7677bb6ce07c40c0 (diff)
downloadtranslated-content-da78a9e329e272dedb2400b79a3bdeebff387d47.tar.gz
translated-content-da78a9e329e272dedb2400b79a3bdeebff387d47.tar.bz2
translated-content-da78a9e329e272dedb2400b79a3bdeebff387d47.zip
initial commit
Diffstat (limited to 'files/ko/web/javascript/reference/global_objects/object/assign')
-rw-r--r--files/ko/web/javascript/reference/global_objects/object/assign/index.html284
1 files changed, 284 insertions, 0 deletions
diff --git a/files/ko/web/javascript/reference/global_objects/object/assign/index.html b/files/ko/web/javascript/reference/global_objects/object/assign/index.html
new file mode 100644
index 0000000000..38b25d0bd8
--- /dev/null
+++ b/files/ko/web/javascript/reference/global_objects/object/assign/index.html
@@ -0,0 +1,284 @@
+---
+title: Object.assign()
+slug: Web/JavaScript/Reference/Global_Objects/Object/assign
+tags:
+ - ECMAScript 2015
+ - JavaScript
+ - Method
+ - Object
+ - Reference
+ - polyfill
+ - 객체
+ - 레퍼런스
+ - 메소드
+translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign
+---
+<div>{{JSRef}}</div>
+
+<p><strong><code>Object.assign()</code> </strong>메소드는 열거할 수 있는 하나 이상의 출처 객체로부터 대상 객체로 속성을 복사할 때 사용합니다. 대상 객체를 반환합니다.</p>
+
+<p>{{EmbedInteractiveExample("pages/js/object-assign.html")}}</p>
+
+<div class="hidden">
+<p>The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p>
+</div>
+
+<h2 id="구문">구문</h2>
+
+<pre class="syntaxbox">Object.assign(<var>target</var>, ...<var>sources</var>)</pre>
+
+<h3 id="매개변수">매개변수</h3>
+
+<dl>
+ <dt><code>target</code></dt>
+ <dd>대상 객체.</dd>
+ <dt><code>sources</code></dt>
+ <dd>하나 이상의 출처 객체.</dd>
+</dl>
+
+<h3 id="반환_값">반환 값</h3>
+
+<p>대상 객체.</p>
+
+<h2 id="설명">설명</h2>
+
+<p>동일한 키가 존재할 경우 대상 객체의 속성은 출처 객체의 속성으로 덮어쓰여집니다. 후에 출처의 속성은 이전의 출처의 속성과 유사하게 덮어씁니다.</p>
+
+<p><code>Object.assign()</code> 메소드는 열거할 수 있는 출처 객체의 속성만 대상 객체로 복사합니다. 이 메소드는 출처 객체의 <code>[[Get]]</code>, 대상 객체의 <code>[[Set]]</code> 을 사용하여 getter 와 setter 를 호출합니다. 따라서 이는 속성을 단순히 복사하거나 새롭게 정의하는 것이 아니라 할당하는 것입니다. 병합 출처가 getter 를 포함하는 경우 프로토타입으로 새로운 속성을 병합하는 것이 적절하지 않을 수 있습니다. 프로토타입으로 속성의 열거성을 포함한 속성의 정의를 복사하려면 대신 {{jsxref("Object.getOwnPropertyDescriptor()")}} 와 {{jsxref("Object.defineProperty()")}} 를 사용해야합니다.</p>
+
+<p>{{jsxref("String")}} 과 {{jsxref("Symbol")}} 속성 모두가 복사됩니다.</p>
+
+<p>에러가 발생할 수 있는 상황에서는(예, 프로퍼티가 쓰기 불가인 경우), {{jsxref("TypeError")}} 가 발생하며, 에러가 발생하기 전에 속성이 추가되었다면 <code>target</code> 객체는 변경될 수 있습니다.</p>
+
+<p><code>Object.assign()</code> 메소드는 {{jsxref("null")}} 또는 {{jsxref("undefined")}} 출처 값에 대해서는 오류를 던지지 않음을 유의하세요.</p>
+
+<h2 id="예시">예시</h2>
+
+<h3 id="객체_클로닝">객체 클로닝</h3>
+
+<pre class="brush: js">const obj = { a: 1 };
+const copy = Object.assign({}, obj);
+console.log(copy); // { a: 1 }
+</pre>
+
+<h3 id="Deep_Clone" name="Deep_Clone">깊은 클로닝에 대한 주의사항</h3>
+
+<p>깊은 클로닝에 대해서, <code>Object.assign()</code> 은 속성의 값을 복사하기때문에 다른 대안을 사용해야합니다. 출처 값이 객체에 대한 참조인 경우, 참조 값만을 복사합니다.</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="객체_병합">객체 병합</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="같은_속성을_가진_객체_병합">같은 속성을 가진 객체 병합</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="심볼형_속성_복사">심볼형 속성 복사</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="프로토타입_체인의_속성과_열거_불가형_속성은_복사_불가">프로토타입 체인의 속성과 열거 불가형 속성은 복사 불가</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="원시_자료형은_객체로_래핑">원시 자료형은 객체로 래핑</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="예외에_의해_진행중인_복사_작업_중단">예외에 의해 진행중인 복사 작업 중단</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="접근자_복사">접근자 복사</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="폴리필">폴리필</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="명세">명세</h2>
+
+<table class="standard-table">
+ <tbody>
+ <tr>
+ <th scope="col">명세</th>
+ <th scope="col">상태</th>
+ <th scope="col">코멘트</th>
+ </tr>
+ <tr>
+ <td>{{SpecName('ESDraft', '#sec-object.assign', 'Object.assign')}}</td>
+ <td>{{Spec2('ESDraft')}}</td>
+ <td> </td>
+ </tr>
+ <tr>
+ <td>{{SpecName('ES2015', '#sec-object.assign', 'Object.assign')}}</td>
+ <td>{{Spec2('ES2015')}}</td>
+ <td>초기 정의.</td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="브라우저_호환성">브라우저 호환성</h2>
+
+<div class="hidden">
+<p>The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> and send us a pull request.</p>
+</div>
+
+<p>{{Compat("javascript.builtins.Object.assign")}}</p>
+
+<div id="compat-mobile"> </div>
+
+<h2 id="함께_보기">함께 보기</h2>
+
+<ul>
+ <li>{{jsxref("Object.defineProperties()")}}</li>
+ <li><a href="/ko/docs/Web/JavaScript/Enumerability_and_ownership_of_properties">속성의 열거성과 소유권</a></li>
+ <li><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Spread_in_object_literals">객체 리터럴에서의 Spread</a></li>
+</ul>