원시데이터타입과 참조타입

Javascript 2022. 1. 23. 00:27
반응형
const number = 1;
const num2 = number;
console.log(num2);
//숫자, 문자, bool, 은 원시타입 종류
//언제든지 다른 변수에 변수를 재할당하면 값을 복사한다

//객체와 배열은 참조타입이다
const person = {
  name: "hong",
};
const person2 = person;
console.log(person2);
console.log(person === person2);

객체인 person은 메모리에 저장되고 person2는 메모리에 포인터를 저장한다 (person을 가리키는 주소값)

person을 person2에 할당하면 포인터가 복사 된다 

그러므로 두 변수의 값(포인터)는 같은 객체를 가리키게 되는 것이다 

person 의 이름을 바꾸면 person2의 이름도 변경된다 

 

 하지만 다음은 다르다 

새로운 객체로 복사 되었기 때문이 다 

const person = {
  name: "hong",
};

const person2 = {
  ...person,
};

console.log(person === person2); //false

person 의 name속성을 변경해도 person2의 name은 변경되지 않는다 

const person = {
  name: "hong",
};

const person2 = {
  ...person,
};

console.log(person === person2);

console.log(person.name);   //hong
console.log(person2.name);  //hong

person.name = "lim";
console.log();

console.log(person.name);   //lim
console.log(person2.name);  //hong
반응형

'Javascript' 카테고리의 다른 글

Array functions  (0) 2022.01.23
Destructuring 구조분해 할당  (0) 2022.01.23
spead, rest operator  (0) 2022.01.22
infinite scrolling  (0) 2021.01.19
즉시실행함수(IIFE) : 익명의 함수 표현  (0) 2020.09.28
: