반응형
SMALL
값과 참조의 차이 (copy by value, copy by reference)
데이터 타입
원시 타입(Primitive)
- number, string, boolean, null, undefined, Symbol
- 메모리 셀 안에 값(value)이 바로 들어가 있음
- 변수가 그 메모리 자체를 가리키고 있음

a변수에 1을 할당하고 변수 b에 a를 할당
a가 가리키고 있는 메모리 값(value)의 1이 복사 되어서 b에도 할당이 됨 → copy by value라 함
원시타입은 값 자체가 복사되어 전달됨
let a = 1;
b = a;
console.log(b); //1
b = 2;
console.log(b); //2
다시 변수 b에 2를 재할당하면 b가 가리키고 있는 메모리 주소에 값이 2로 바뀜
객체 타입(Object)
- 메모리 셀 안에 실제 객체가 들어가 있는 메모리 주소가 들어가 있음

let apple = {
color: 'red'
}
let banana = apple; //apple 객체 할당
console.log(banana);
banana변수에 apple을 할당
apple이 가리키고 있는 메모리에 들어 있는 메모리 주소가 복사되어 할당이 됨 → copy by reference라 함
객체타입은 참조값(메모리주소, 레퍼런스)가 복사되어 전달됨

let apple = { // 0x000003
color: 'red'
}
let banana = apple; // 0x000003
apple.color = 'yellow';
console.log(apple); //{ color: 'yellow' }
console.log(banana); //{ color: 'yellow' }

주의해야할 점
apple 객체의 color 값을 변경하면 apple 객체의 color와 banana 객체의 color가 모두 변경이 됨
→ 한곳에서만 변경을 하더라도 동일하게 변경이 됨
* 참고
반응형
LIST
'Javascript' 카테고리의 다른 글
[Javascript] 일급, 일급함수, 고차함수 개념 (0) | 2023.04.09 |
---|
댓글