객체를 생성하기 위해서 객체리터럴을 사용할 수 도 있지만, 프로퍼티 구조가 동일하면서 매번 같은 프로퍼티와 매서드를 기술해야 할 때 어려운 점이 있다. 생성자 함수는 여러 개의 객체를 간편하게 생성하는 것을 도와준다. 생성자 함수와 프로토 타입을 함께 사용하면 객체 지향 프로그래밍의 기본개념은 자바스크립트에서 구현할 수 있다.
(예시)
function Circle(radius){
this.radius = radius;
this.getDiameter =function(){
return 2*this.radius
}
}
const circle1 = new Circle(5);
const circle2 = new Circle(10);
console.log(circle1.getDiameter()); //10
console.log(circle2.getDiameter()); //20
// 생성자 함수 정의
function Person(name, age) {
// this 키워드를 사용하여 현재 생성되는 객체에 속성을 할당
this.name = name;
this.age = age;
// 메서드도 추가 가능
this.sayHello = function() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
};
}
// 생성자 함수를 사용하여 객체 생성
let person1 = new Person('John', 30);
let person2 = new Person('Alice', 25);
// 객체의 속성과 메서드 사용
console.log(person1.name); // John
person1.sayHello(); // Hello, my name is John and I'm 30 years old.
console.log(person2.name); // Alice
person2.sayHello(); // Hello, my name is Alice and I'm 25 years old.