Programming/JavaScript

[JavaScript] 자바스크립트 객체 복사 Copying objects in javascript

통통만두 2018. 11. 8. 08:13
반응형


자바스크립트에서 객체 복사에 대해서 알아보도록 하겠습니다. 객체 복사에는 크게 얕은 복사(Shallow Copy)깊은 복사(Deep Copy)가 있습니다. 우선 아래의 예제를 살펴보도록 하겠습니다.


얕은 복사(Shallow Copy)

var user = {
    name: 'marsland.tistory.com'
}
console.log(user.name);    // marsland.tistory.com
 
var customer = user;
console.log(customer.name);    // marsland.tistory.com
 
user.name = 'great marsland.tistory.com';
console.log(user.name);    // great marsland.tistory.com
console.log(customer.name); // great marsland.tistory.com
 
customer.name = 'good marsland.tistory.com';
console.log(user.name);    // good marsland.tistory.com
console.log(customer.name); // good marsland.tistory.com

위의 예제와 같이 user과 customer은 어느쪽을 수정하든 같이 반영됩니다. 이를 얕은 복사(Shallow Copy)라고 하며 예제에서는 user값을 customer객체에 대입하지만 이는 단지 주소값을 공유할 뿐입니다. 쉽게 말해서 user객체와 customer객체는 동일한 객체를 가리킵니다. 


깊은 복사(Deep Copy)

var user = {
    name: 'marsland.tistory.com'
}
console.log(user.name);    // marsland.tistory.com
 
var userDeepCopy = $.extend(true, {}, user);
userDeepCopy.name = 'deep marsland.tistory.com';
console.log(user.name); // marsland.tistory.com
console.log(userDeepCopy.name); // deep marsland.tistory.com
jQuery 플러그인의 $.extend를 사용한 깊은 복사(Deep Copy) 예제입니다. userDeepCopy 객체user 객체와는 별도의 주소에 저장이 되기 때문에 user 객체userDeepCopy 객체간에는 서로 영향을 주지 않습니다.


얕은 복사(Shallow Copy)깊은 복사(Deep Copy)는 위에 소개해드린 방법 이외에 다양한 방법들이 있습니다. 우리가 기억해야 할 중요한 것은 상황에 맞게 얕은 복사(Shallow Copy)깊은 복사(Deep Copy)를 사용해야 할지 정하는 것입니다.


반응형