1. 원시값, 참조값
원시값을 변수에 할당하면 실제값이 저장됨
객체를 변수에 할당하면 참조값(메모리 주소)이 저장됨
2. 얕은 복사
원래값과 복사된 값이 같은 참조를 가리키고 있는 것
객체안에 객체가 있을 경우 어느 하나라도 원본 객체를 참조하고 있다면 얕은 복사임
1 depth까지만 깊은 복사가 이루어짐
- Object.assign
- ... ({...객체} / [...배열])
를 사용하여 얕은 복사를 할 수 있음
const a = { b: { c: 'c' }, e: 'e' }
const b = {...a}
console.log(a) // { b: { c: 'c' }, e: 'e' }
console.log(b) // { b: { c: 'c' }, e: 'e' }
b.e = 'd'
console.log(a) // { b: { c: 'c' }, e: 'e' }
console.log(b) // { b: { c: 'c' }, e: 'd' }
b.b.c = 'z'
console.log(a) // { b: { c: 'z' }, e: 'e' }
console.log(b) // { b: { c: 'z' }, e: 'd' }
3. 깊은 복사
참조를 모두 끊어버리고 새롭게 복사하는 것
원시값의 복사는 기본적으로 깊은 복사임
const a = 'a';
const b = a;
- 다른 사람이 만들어 둔 커스텀 함수 or 라이브러리
- JSON.parse(Json.Stringify(Object))
를 사용하여 깊은 복사를 할 수 있음
const a = { b: { c: 'c' }, e: 'e' }
const b = JSON.parse(JSON.stringify(a))
console.log(a) // { b: { c: 'c' }, e: 'e' }
console.log(b) // { b: { c: 'c' }, e: 'e' }
b.e = 'd'
console.log(a) // { b: { c: 'c' }, e: 'e' }
console.log(b) // { b: { c: 'c' }, e: 'd' }
b.b.c = 'z'
console.log(a) // { b: { c: 'c' }, e: 'e' }
console.log(b) // { b: { c: 'z' }, e: 'd' }
내부 | 외부 | |
참조 | true | true |
얕은 복사 | true | false |
깊은 복사 | false | false |
'js' 카테고리의 다른 글
[javascript] 생성자 함수(new)와 클래스(class) (0) | 2022.10.28 |
---|---|
[javascript] this란? (0) | 2022.10.28 |
[javascript] 난수 생성하는 방법 (Math.random) (0) | 2022.10.26 |
[javascript] 이벤트 버블링(bubbling), 캡처링(capturing) (0) | 2022.10.25 |
[javascript] Array every(), some() (0) | 2022.10.25 |