각각 연필과 색연필의 class가 있다.
두개의 공통점은 각각 색이 있고, 깎을 수 있고 부러질 수 있다.
하지만 색연필은 추가로 색칠할 수 있다.
이처럼 연필과 색연필에 공통점이 있기 때문에상속
을 통하여 특징들을 가져올 수 있다.
// 부모
class Stationery {
constructor(color) {
this.color = color;
}
sharpening() {
console.log('깎자');
}
broken() {
console.log('부러지지마');
}
}
// extends를 통해 부모클래스 Stationery를 상속할 수 있다.
class Pencil extends Stationery {}
const green = new Pencil('초록');
console.log(green);
green.broken();
// 자식요소에 필요한 함수나 속성을 추가할 수 있다.
class ColorPencil extends Stationery {
coloring() {
console.log('색칠하다');
}
}
const yellow = new ColorPencil('노랑');
console.log(yellow);
yellow.broken();
yellow.coloring();
constructor로 부터 외부에서 가져오기가 가능하다.
대신 자식 class 에서 constructor를 정의하는 순간 부
모에 있던 것들을 다 받아와야 한다.
부모Class의 생성자(constructor)를 참조한다.
suepr : https://velog.io/@growgrow_up/Javascriptsuper
부모 Class로 부터 받은 메서드와 같은 이름의 내용이 다른 매서드를 재정의해 덮어 씌우는 방식.
class Stationery {
constructor(color) {
this.color = color;
}
sharpening() {
console.log('깎자');
}
broken() {
console.log('부러지지마');
}
}
// extends를 통해 부모클래스 Stationery를 상속할 수 있다.
class Pencil extends Stationery {}
const green = new Pencil('초록');
//console.log(green);
//green.broken();
// 자식요소에 필요한 함수나 속성을 추가할 수 있다.
class ColorPencil extends Stationery {
constructor(color, owner) {
super(color);
this.owner = owner;
}
coloring() {
console.log('색칠하다');
}
sharpening() {
// 부모의 기능을 유지하면서 추가적으로 하고싶을 때
super.sharpening();
console.log('연필깎이로 깎자');
}
}
const yellow = new ColorPencil('노랑', '석봉');
console.log(yellow);
yellow.broken();
yellow.coloring();
yellow.sharpening();