객체 지향 프로그래밍의 특징으로 Polymorphism 다형성 있다.
즉, 부모 클래스에서 정의한 하나의 매서드를 각 자식 클래스특성에 맞게 다르게 변형해서 사용할 수 있다.
먼저 extends
를 사용하면 클래스를 확장하여 자식 클래스를 만들 수 있다.
class Book {
constructor(title, author) {
this.title = title;
this.author = author;
}
circulation() {
console.log("몇 부나 팔렸을까..");
}
}
class Novel extends Book {}
let 해리포터 = new Novel("해리포터", "J.K.롤링");
console.log(해리포터.author); // J.K.롤링
해리포터.circulation(); // 몇 부나 팔렸을까..
자식 클래스에서 동일한 이름으로 메서드를 정의하면 내용을 덮어쓰고(overriding), 더이상 부모의 매서드가 호출되지 않는다.
class Book {
constructor(title, author) {
this.title = title;
this.author = author;
}
circulation() {
console.log("몇 부나 팔렸을까..");
}
}
class Novel extends Book {
circulation() {
console.log("소설의 판매 부수는..");
}
}
let 해리포터 = new Novel("해리포터", "J.K.롤링");
해리포터.circulation(); // 소설의 판매 부수는..
자식 클래스의 매서드를 사용할 때 부모 클래스의 매서드도 불러와서 함께 사용하고 싶다면 매서드를 오버라이딩할 때 super
키워드를 사용하면 된다.
class Book {
constructor(title, author) {
this.title = title;
this.author = author;
}
circulation() {
console.log("몇 부나 팔렸을까..");
}
}
class Novel extends Book {
circulation() {
super.circulation();
console.log("소설의 판매 부수는..");
}
}
let 해리포터 = new Novel("해리포터", "J.K.롤링");
해리포터.circulation();
// 몇 부나 팔렸을까..
// 소설의 판매 부수는..
매서드 외 생성자 함수(constructor)
를 오버라이딩하거나 매서드를 추가할 때에는 먼저 super
로 부모 클래스의 constructor 를 불러온 뒤 사용해주어야 한다.
class Book {
constructor(title, author) {
this.title = title;
this.author = author;
}
}
/* 부모 클래스의 constructor를 super로 호출하지 않은 경우 */
class Novel extends Book {
constructor(series) {
this.series = series;
}
}// ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
let 해리포터 = new Novel("해리포터", "J.K.롤링");
class Book {
constructor(title, author) {
this.title = title;
this.author = author;
}
}
/* constructor의 super 를 호출할 때 파라미터도 잘 전달해주어야 한다. */
class Novel extends Book {
constructor(title, author, series) {
super(title, author); // super은 this 보다 위에 써주어야 한다.
this.series = series;
}
}
let 해리포터 = new Novel("해리포터", "J.K.롤링", 7);
console.log(해리포터); // Novel { title: '해리포터', author: 'J.K.롤링', series: 7 }
자식 클래스에서 constructor 를 따로 오버라이딩 하지 않은 경우에는 자식클래스에서 따로 생성자 함수를constructor 작성하지 않아도 아래 코드처럼 동작하고 있다.
class Book {
constructor(title, author) {
this.title = title;
this.author = author;
}
}
class Novel extends Book {
/* 아래 두 줄을 생략해도 자바스크립트가 자동으로 동작한다. */
// constructor(...rest) {
// super(...rest);
}
}