서로 다른 클래스나 생성자 함수가 같은 속성들을 공유할 때
이들의 관계를 정의함으로써 코드의 중복을 줄이고 효율을 높임
- "B클래스는 A클래스에서 파생된다." - "B는 A의 하위분류"
class Bird {
wings = 2;
}
class Eagle extends Bird {
claws = 2;
}
class Penguin extends Bird {
swim () { console.log('수영중...'); }
}
class EmperorPenguin extends Penguin {
size = 'XXXL';
}
// 인스턴스 생성
const birdy = new Bird();
const eaglee = new Eagle();
const pengu = new Penguin();
const pengdol = new EmperorPenguin();
for (const i of [
[ '1.', birdy instanceof Bird ], // 1. true
[ '2.', eaglee instanceof Bird ], // 2. true
[ '3.', eaglee instanceof Eagle ], // 3. true
[ '4.', pengdol instanceof Penguin ], // 4. true
[ '5.', pengdol instanceof Bird ], // 5. true
[ '6.', birdy instanceof Eagle ] // 6. false
]) {
console.log(i[0], i[1]);
}
// 치킨집 클래스 생성
class YalcoChicken {
no = 0;
menu = { '후라이드': 10000, '양념치킨': 12000 };
constructor (name, no) {
this.name = name;
if (no) this.no = no;
}
introduce () {
return `안녕하세요, ${this.no}호 ${this.name}점입니다!`;
}
order (name) {
return `${this.menu[name]}원입니다.`
}
}
// 치킨집의 자식클래스 카페
class YalcoChickenAndCafe extends YalcoChicken {
cafeMenu = { '아메리카노': 4000, '라떼': 4500 };
cafeOrder (name) {
return `${this.cafeMenu[name]}원입니다.`
}
}
const chain1 = new YalcoChickenAndCafe('서면', 2)
console.log(chain1);
console.log(
chain1.order('후라이드'),
chain1.cafeOrder('라떼')
);
자식 클래스에서 부모로부터 물려받은 속성이나 기능을 덮어씀
class Bird {
wings = 2;
canFly = true;
travel () { console.log('비행중...') }
}
class Eagle extends Bird {
claws = 2;
}
class Penguin extends Bird {
canFly = false; // 부모 Bird의 속성을 덮어씀
travel () { console.log('수영중...') } // 부모 Bird의 기능을 덮어씀
}
const eaglee = new Eagle();
const pengu = new Penguin();
console.log(eaglee);
eaglee.travel();
console.log(pengu);
pengu.travel();
super
: 자식 클래스에서 부모 클래스의 constructor 또는 메서드 호출