# 깊은 복사

재귀함수로 객체를 복사하는 방법(객체의 속성이 객체를 담고 있을 때)

```javascript
function copyObj(obj) {
    var copy = {};
    if(typeof obj === 'object' && obj !== null) {
        for(var attr in obj) {
            if(obj.hasOwnProperty(attr)) {
                 copy[attr] = copyObj[obj][attr]);
             }
         }
     }else {
         copy = obj;
     }
     return copy;
 }
```

가장 간단하게 복사하는 방법 : JSON이용.

```javascript
var obj = {a: 1, b: { c:3},};//b는 다른 객체를 갖는다
var obj2 = {};
Object.keys(obj);

obj2 = JSON.parse(JSON.stringify(obj))
obj2.a = 4;
obj.a = 1;//값이 변하지 않고 그대로다.
obj2.b.c = 8;
obj.b.c = 1;//값이 바뀌어버렸다.

```

위의 대안들도 수많은 예외상황이 존재하기 때문에 사실상 객체의 깊은복사는 어렵다.&#x20;

아래 코드는 slice를 사용하여 배열을 깊은복사하는 방법이다. 하지만 이 방법도 껍데기만 깊은 복사이고 속은 얕은 복사이다. Object.key와 forEach문을 이용했을 때와 비슷하다.

```javascript
arr = [1,2,3];
arr2 = arr.slice();//참조관계를 끊으며 복사.
```

```javascript
var obj3 = JSON.parse(JSON.stringify(obj1));//복사

```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://heunnajo.gitbook.io/zerocho-javascript/undefined-26.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
