반응형
자바스크립트 class에 대해 알게되었다.
class 끼리 extends 키워드로 상속이라는게 가능하다.
class Pet {
constructor(name, age){
this.name = name;
this.age = age;
}
eat(){
const {name} = this;
return console.log(`${name}(이)가 밥을 먹었다.`);
}
}
class Cat{
constructor(name, age){
this.name = name;
this.age = age;
}
eat(){
const {name} = this;
return console.log(`${name}(이)가 밥을 먹었다.`);
}
meow(){
const {name} = this;
return console.log(`${name}(이)가 냐옹했다.`);
}
todos(){
const {name, todo} = this;
return console.log(`${name}이 ${todo} 중..`);
}
}
class Dog{
constructor(name, age){
this.name = name;
this.age = age;
}
eat(){
const {name} = this;
return console.log(`${name}(이)가 밥을 먹었다.`);
}
bow(){
const {name} = this;
return console.log(`${name}(이)가 짖었다.`);
}
}
const pet = new Pet(`bob`, 15);
const cat = new Cat(`cha`, 15);
const dog = new Dog(`yoyo`, 15);
Pet과 Cat, Dog클래스가 있다.
다 같은 메소드 eat과 생성자를 쓰고 있는 비효율적인 상황이다.
이럴때 extends 키워드를 쓰면 Cat과 Dog를 Pet에 종속시킬 수 있다.
class Pet {
constructor(name, age){
this.name = name;
this.age = age;
}
eat(){
const {name} = this;
return console.log(`${name}(이)가 밥을 먹었다.`);
}
}
class Cat extends Pet{
constructor(name, age, todo){
super(name, age)
this.todo = todo;
}
meow(){
const {name} = this;
return console.log(`${name}(이)가 냐옹했다.`);
}
todos(){
const {name, todo} = this;
return console.log(`${name}이 ${todo} 중..`);
}
}
class Dog extends Pet{
constructor(name, age){
super(name, age)
}
bow(){
const {name} = this;
return console.log(`${name}(이)가 짖었다.`);
}
}
const cat = new Cat('bob', 10, '산책');
extends로 확장 시키면
부모로 부터 생성자를 호출할 수 있다.
바로 super 라는 키워드 이다.
추가로 필요한 값들은 자식클래스에 추가해서 사용하면 된다.
잘 동작한다.
객체 지향을 공부하면서 class를 사용해보았는데
그 전보다 extends와 super로 인해서 코드의 중복이 훨씬 줄어들었다.
반응형
'javascript' 카테고리의 다른 글
[JS] netERRABORTED-404-Not-Found-에러 (0) | 2023.10.21 |
---|---|
[JS] 쓰로틀링, 디바운스 (0) | 2023.08.05 |
[JS] 객체 지향 프로그래밍(OOP) 팩토리 함수, 생성자 함수, class (0) | 2023.04.18 |
[JS] axios와 headers (2) | 2023.04.17 |
[JS] fetch 와 XHR (0) | 2023.04.16 |