깊은 복사 ? 얕은 복사?

2025. 5. 29. 15:37JS

 

다음과 같은 질문에 답은 뭘까?

1. userB의 출력값은 뭘까?

const userA = { name:"Tom", profile :{email:"Tom12@gmail.com"}};
const userB = {...userA}

userA.name="Mon"
userA.profile.email = "Mon12@gmail.com"

console.log(userB)

 

자칫하면 ' {name :"Mon", profile:{email:"Mon12@gmail.com"}} ' 으로 생각할 수 있다.

userB는 userA의 얕은 복사본을 생성한다. 

name 속성이 얕은 복사 과정에서 '값'으로 복사가 되므로 userB.name에는 영향을 주지 않는다 .

여기서 name이 그저 문자열이고, 문자열은 기본형(primitive) 이기 때문에 복사할 때 값그대로 'Tom'을 그냥 복제한다.

객체 내부의 객체 (profile)는 참조로 복사가 된다.

따라서 userA.profile.email 값을 변경하면, 이 변경사항이 참조된 userB.profile.email에 반영이 된다.

즉, email은 객체 속 객체 안에 있기 때문에 참조 공유하여 내부 속성(email) 변경 시 같이 바뀐다!!

 

(참조 공유: 두 변수가 같은 객체를 가리킨다 , 값을 새로 복사하는 게 아니라, 원래 객체의 주소(참조)를 복사)

 

 

따라서 답은 !! 

{name:" Tom", profile:{email:"Mon12@gmail.com"}} 이다.