객체 생성자는 함수를 통해서 새로운 객체를 만들고 그 안에 넣고 싶은 값 혹은 함수들을 구현할 수 있게 해준다.
function Animal(type, name, sound) {
this.type = type;
this.name = name;
this.sound = sound;
this.say = function() {
console.log(this.sound);
};
}
const dog = new Animal('개', '멍멍이', '멍멍');
const cat = new Animal('고양이', '야옹이', '야옹');
dog.say(); // 멍멍
cat.say(); // 야옹
객체 생성자를 사용할 때는 보통 함수의 이름을 대문자로 시작하고, 새로운 객체를 만들 때에는 new 키워드를 앞에 붙여주어야 한다.
위 코드에서는 dog가 가지고 있는 say 함수와 cat이 가지고 있는 say 함수가 똑같음에도 불구하고 객체가 생성될 때마다 함수도 새로 만들어져 this.say로 설정이 되고 있다.
같은 객체 생성자 함수를 사용하는 경우, 특정 함수 또는 값을 재사용할 수 있는데 이게 바로 프로토타입이다. 프로토타입은 다음과 같이 객체 생성자 함수 아래에 .prototype.[원하는키] = 코드를 입력하여 설정할 수 있다.
function Animal(type, name, sound) {
this.type = type;
this.name = name;
this.sound = sound;
}
Animal.prototype.say = function() {
console.log(this.sound);
};
Animal.prototype.sharedValue = 1;
const dog = new Animal('개', '멍멍이', '멍멍');
const cat = new Animal('고양이', '야옹이', '야옹');
dog.say(); // 멍멍
cat.say(); // 야옹
console.log(dog.sharedValue); // 1
console.log(cat.sharedValue); // 1
Animal의 기능을 재사용해서 Cat과 Dog이라는 새로운 객체 생성자를 만든다고 할 때, 다음과 같이 구현할 수 있다.
function Animal(type, name, sound) {
this.type = type;
this.name = name;
this.sound = sound;
}
Animal.prototype.say = function() {
console.log(this.sound);
};
Animal.prototype.sharedValue = 1;
function Dog(name, sound) {
Animal.call(this, '개', name,sound);
}
Dog.prototype = Animal.prototype;
function Cat(name, sound) {
Animal.call(this, '고양이', name, sound);
}
Cat.prototype = Animal.prototype;
const dog = new Dog('멍멍이', '멍멍');
const cat = new Cat('야옹이', '야옹');
dog.say(); // 멍멍
cat.say(); // 야옹
새로 만든 Dog와 Cat 함수에서 Animal.call을 호출해 주고 있다. Animal.call의 첫 번째 인자에는 this를 넣어줘야 하고, 그 이후에는 Animal 객체 생성자 함수에서 필요로 하는 파라미터를 넣어줘야 한다. 추가적으로 prototype을 공유해야 하기 때문에 상속받은 객체 생성자 함수를 만들고 나서 prototype 값을 Animal.prototype으로 설정했다.
ES6에서부터 class 문법이 추가되었다. class를 사용하면 객체 생성자로 구현했던 코드를 더 명확하고 깔끔하게 구현할 수 있다. 추가적으로 상속도 훨씬 쉽게 할 수 있다.
class Animal {
constructor(type, name, sound) {
this.type = type;
this.name = name;
this.sound = sound;
}
say() {
console.log(this.sound);
}
}
const dog = new Animal('개', '멍멍이', '멍멍');
const cat = new Animal('고양이', '야옹이', '야옹');
dog.say(); // 멍멍
cat.say(); // 야옹
여기서 say라는 함수를 클래스 내부에 선언했는데, 클래스 내부의 함수를 '메서드'라고 부른다. 이렇게 메서드를 만들면 자동으로 prototype으로 등록된다.
class를 사용했을 때 다른 클래스를 쉽게 상속할 수 있다.
class Animal {
constructor(type, name, sound) {
this.type = type;
this.name = name;
this.sound = sound;
}
say() {
console.log(this.sound);
}
}
class Dog extends Animal {
constructor(name, sound) {
super('개', name, sound);
}
}
class Cat extends Animal {
constructor(name, sound) {
super('고양이', name, sound);
}
}
const dog = new Dog('멍멍이', '멍멍');
const dog2 = new Dog('왈왈이', '왈왈');
const cat = new Cat('야옹이', '야옹');
const cat2 = new Cat('냐옹이', '냐옹');
dog.say(); // 멍멍
dog2.say(); // 왈왈
cat.say(); // 야옹
cat2.say(); // 냐옹
상속을 할 때는 extends 키워드를 사용하며, constructor에서 사용하는 super() 함수가 상속받은 클래스의 생성자를 가리킨다.