
생성자 함수는 새로운 객체를 생성할 때 사용되는 특수한 함수.
이 함수는 new 키워드와 함께 호출되며, 호출 시 새로운 인스턴스 반환.
생성자 함수의 이름은 대문자로 시작하는 것이 관례.
대문자로 시작하는 이유
new 키워드 없이 호출하는 실수를 줄이는 데 도움예시
function Person(name, age) {
this.name = name;
this.age = age;
}
const person1 = new Person("윤지", 18);
console.log(person1.name); // 출력: 윤지
console.log(person1.age); // 출력: 18
Person 함수는 생성자 함수로 사용됨new 키워드로 객체 생성 시, this는 새로 생성된 객체를 가리킴this.name과 this.age는 새 객체의 속성으로 설정됨매개변수만 변경하여 동일한 구조의 객체를 쉽게 여러 개 생성 가능
이렇게 하면 같은 구조를 가진 여러 객체를 간단하게 생성할 수 있어 코드의 재사용성과 효율성 향상
const person1 = new Person("윤지", 18);
const person2 = new Person("민수", 25);
const person3 = new Person("지영", 30);
const person = {
name: "윤지",
age: 18,
introduce: function() {
console.log(`안녕하세요, 제 이름은 ${this.name}이고 ${this.age}살입니다.`);
}
};
person.introduce(); // 출력: 안녕하세요, 제 이름은 윤지이고 18살입니다.
function Person(name, age) {
this.name = name;
this.age = age;
this.introduce = function() {
console.log(`안녕하세요, 제 이름은 ${this.name}이고 ${this.age}살입니다.`);
}
}
const person = new Person("윤지", 18);
person.introduce(); // 출력: 안녕하세요, 제 이름은 윤지이고 18살입니다.
function User(name, age) {
this.name = name;
this.age = age;
}
const u = new User("철수", 30);
console.log(u); // User { name: '철수', age: 30 }
아래 사진: 위는 객체 리터럴, 아래는 생성자 함수로 생성된 객체
생성자 함수로 만든 객체: 중괄호 앞에 User 표시됨

function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.introduce = function() {
console.log(`안녕하세요, 제 이름은 ${this.name}이고 ${this.age}살입니다.`);
};
const person1 = new Person("윤지", 18);
const person2 = new Person("민수", 25);
person1.introduce(); // 출력: 안녕하세요, 제 이름은 윤지이고 18살입니다.
person2.introduce(); // 출력: 안녕하세요, 제 이름은 민수이고 25살입니다.
프로토타입 사용 시 모든 인스턴스가 같은 메서드를 공유하여 메모리 사용 절약됨
function 동물차트(이름, 종류, 나이, 주인) {
this.이름 = 이름;
this.종류 = 종류;
this.나이 = 나이;
this.주인 = 주인;
this.방문기록 = [];
this.방문추가 = function(날짜, 이유, 치료) {
this.방문기록.push({ 날짜, 이유, 치료 });
}
this.마지막방문 = function() {
if (this.방문기록.length > 0) {
return this.방문기록[this.방문기록.length - 1];
}
return "방문 기록 없음";
}
}
const 고양이 = new 동물차트("나비", "고양이", 3, "김철수");
const 강아지 = new 동물차트("멍멍이", "개", 5, "이영희");
고양이.방문추가("2024-10-25", "정기검진", "예방접종");
강아지.방문추가("2024-10-28", "다리 부상", "붕대");
console.log(고양이.이름); // 출력: 나비
console.log(강아지.마지막방문()); // 출력: { 날짜: '2024-10-28', 이유: '다리 부상', 치료: '붕대' }
이 예제에서 생성자 함수를 사용해 동물병원 차트 구현. 객체마다 독립적인 방문 기록 관리 가능함
시간 객체를 생성하는 생성자 함수 정의. 각 인스턴스는 시간을 표시하는 기능 제공
function Time(hour, minute, seconds) {
this.hour = hour;
this.minute = minute;
this.seconds = seconds;
this.getTime = function () {
return `${this.hour}:${this.minute}:${this.seconds}`;
};
}
const time1 = new Time(15, 30, 27);
console.log(time1.getTime());
// Time 생성자 함수 정의
function Time(hours, minutes, seconds) {
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
this.toString = function() {
return `${this.padZero(this.hours)}:${this.padZero(this.minutes)}:${this.padZero(this.seconds)}`;
};
this.padZero = function(num) {
return num.toString().padStart(2, '0');
};
}
// Time 객체 생성 및 사용 예제
const currentTime = new Time(14, 30, 0);
console.log(currentTime.toString()); // "14:30:00"
const lateNight = new Time(23, 59, 59);
console.log(lateNight.toString()); // "23:59:59"
instanceof 연산자인스턴스: 생성자 함수를 통해 생성된 객체
instanceof 연산자: 객체가 특정 생성자 함수로부터 만들어졌는지 확인 가능
예시: Person 생성자 함수로 만든 person1, person2은 모두 Person의 인스턴스
const person1 = new Person("윤지", 18);
const person2 = new Person("민수", 25);
console.log(person1 instanceof Person); // 출력: true
console.log(person2 instanceof Person); // 출력: true
각 인스턴스는 생성자 함수에서 정의한 속성과 메서드를 가지며, 서로 독립적인 객체임. 한 인스턴스의 변경이 다른 인스턴스에 영향을 미치지 않음