[JS] Day14 - Reference VS Copying

jiseong·2021년 8월 31일
0

T I Learned

목록 보기
48/291

Day14 - Reference VS Copying

🎯 기능 요구사항

  • Shallow Copy와 Deep Copy에 대해 알아본다.

🚀 배운 점

Shallow Copy와 Deep Copy

이전에 메모리 모델을 공부한 덕분에 Day14 이해에 많은 도움이 되었다.
하지만, 하나 몰랐던 점이 있었는데 object copy를 할 때 아래와 같이 기존에 사용하던 방식을 이용하면 1 level deep copy만 일어난다는 점이다.

const wes = {
    name: 'wes',
    age: '90',
    social: {
    	twitter: 'a',
        facebook: 'b'
    }
};

const tempObj = {...wes};
//or
const tempObj = Object.assign({}, wes);

여기서 tempObj.social.twitter = 'test'로 변경하면 복사한 기존의 wes도 변경되게 된다.
tempObj.name = 'test'로 변경해도 1 level deep copy이기 때문에 기존의 wes는 변경되지 않는다.

이를 해결하기 위해서는 라이브러리, 커스텀 함수 또는 느리지만 JSON.stringify() 와 JSON.parse()를 이용해야 한다.

직접 구현해보고 싶어 아래와 같이 커스텀 함수를 만들어봤다.

const isObject = (val) => typeof val === 'object';

const deepCopyObject = (obj) => {
    if(obj === null || !isObject(obj)) return obj;

    let clone = {};
    for(let key in obj){
        clone[key] = deepCopyObject(obj[key]);
    }

    return clone;
}

const tempObj2 = deepCopyObject(wes);
tempObj2.social.twitter = 'deepCopy';

console.log(wes.social.twitter === tempObj2.social.twitter); // false

위의 커스텀 함수도 문제점이 있는데 Date type일 때 정상적으로 작동되지 않는다. 스택오버플로우에 다양한 커스텀함수와 이야기들이 있으니 참고하면 좋을 듯 하다.


Reference

0개의 댓글