클래스를 활용한 상속
class Animal {
constructor(age, weight) {
this.age = age;
this.weight = weight;
}
eat() {
return "eat";
}
move() {
return "move";
}
}
class Bird extends Animal {
constructor(age, weight) {
super(age, weight);
}
fly() {
return "fly";
}
}
프로토타입을 기반으로 한 상속
const Animal = (function () {
function Animal(age, weight) {
this.age = age;
this.weight = weight;
}
return Animal;
})();
const Bird = (function () {
function Bird(age, weight) {
Animal.apply(this, [age, weight]);
}
Bird.prototype = Object.create(Animal.prototype);
Bird.prototype.constructor = Bird;
return Bird;
})();
클래스와 생성자 함수의 차이점
- 클래스는 new 없이 호출할 경우 error가 발생합니다.
- 클래스 내의 모든 코드에는 암묵적으로 strict mode가 지정되어 실행되며 strict mode를 해제할 수 없습니다.
- 클래스 내의 메서드 및 정적 메서드는 모두 [[Enumable]]이 false 입니다.
- 클래스를 통해 상속을 구현한다면, 부모 클래스와 자식 클래스의 인스턴스 프로토타입 체인뿐만 아니라 클래스간의 프로토타입 체인도 생성합니다.