■ Reference Data Type
Data Type의 종류
자바스크립트 자료형의 데이터 타입은 Primitive 와 Reference 로 분류가 됩니다.
Primitive 데이터 타입들은 자료 자체가 변수에 저장되는 자료들로 문자, 숫자 자료형들이 대표적입니다.
Reference 데이터 타입들은 변수가 저장된 값을 가리키고 있으며 Array, Object 자료형 등이 있습니다. 즉, Array, Object 자료형으로 만든 변수는 메모리에 저장된 객체의 위치를 참조합니다.
// Primitive data type
var name = 'john';
var age = 20;
// Reference data type
var 사람 = { name : 'Kim' };
Reference Data Type 예제
예제1
var 이름1 = { name : '김' };
var 이름2 = 이름1;
이름1.name = '박';
// 이름1과 이름2 둘 다 { name : '박' }이라고 나옵니다.
이름1의 name 값만 변경하였기 때문에, 이름2는 name: '김' 이 나올 것 같지만 name:'박' 이 나옵니다.
Reference 데이터 타입은 Primitive 데이터 타입과 다르게 변수에 값을 저장하는 것이 아닌 위치를 참조합니다.
즉, 이름2와 이름1은 서로 같은 객체를 참조하고 있으므로 동일한 변경 결과를 보입니다.
예제2
var 이름1 = { name : '김' };
var 이름2 = { name : '김' };
// 이름1 == 이름2 은 false 값을 보냅니다.
이름1과 이름2가 같은 변수로 보이므로, 값을 비교하면 true 가 나올 것 같지만 false가 나옵니다.
왜냐하면 이름1과 이름2는 모두 Object 형태의 변수이므로, 서로 다른 메모리 공간에 저장되어 다른 객체입니다.
예제3
var 이름1 = { name : '김' };
function 변경(obj){
obj = { name : 'park' };
}
변경(이름1);
// 함수를 실행해도 이름1의 값이 바뀌지 않습니다.
name의 값이 park 으로 변경되는 함수를 만들어 실행하였지만 이름1의 name 값은 바뀌지 않았습니다.
obj 변수는 전달된 객체를 참조하고 있을뿐, 이름1이 참조하는 객체와는 별개이므로 변경이 불가능합니다.
즉, 변경(이름1)은 var obj = 이름1 이런 느낌으로 변수를 만든 것이기 때문에, 서로 다른 객체를 참조합니다.
■ constructor 함수
constructor 문법?
constructor는 객체를 만드는데 사용되는 함수로, 생성자 함수라고도 불립니다.
constructor 함수는 new 키워드로 호출되며, 함수 이름의 첫 글자를 대문자로 쓰는 것이 원칙입니다.
function Person(name, age) {
this.name = name;
this.age = age;
this.greet = function() {
console.log(`Hello, my name is ${this.name}`);
}
}
var john = new Person("John", 25);
john.greet(); // 출력: "Hello, my name is John"
함수 안에서 쓰이는 this는 새로 생성되는 객체(인스턴스)를 뜻하며, 물론 파라미터를 넣는 것도 가능합니다.
그리고 constructor가 가진 속성들을 그대로 물려받아서 새로운 객체를 만드는 것을 상속이라고 합니다.
'JavaScript' 카테고리의 다른 글
JavaScript(setter, getter) (0) | 2023.06.14 |
---|---|
JavaScript(prototype과 class를 활용한 상속 기능) (0) | 2023.06.13 |
JavaScript(default parameter, arguments와 rest parameter) (0) | 2023.06.01 |
JavaScript(Spread Operator) (0) | 2023.06.01 |
JavaScript(Tagged literals와 apply, call 함수) (0) | 2023.06.01 |