The Web Developer 부트캠프 2022

JS Class Super, Extend

거위발바닥 2022. 9. 27. 20:28
class Cat {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    eat() {
        const { name } = this; // name객체를 this에서 추출해옴
        return `${name} is eating!` // this에서 추출해온 name을 사용한 return 
    }
    meow() {
        return 'MEOWWW';
    }
}

const blue = new Cat('blue',9) // blue는 object class Cat이며 name blue, age 9

class Dog {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    eat() {
        const { name } = this; // name객체를 this에서 추출해옴
        return `${name} is eating!` // this에서 추출해온 name을 사용한 return 
    }
    bark() {
        return "WOOF!!";
    }
}

해당 코드의 중복되는 부분을 super나 extend를 이용하여 부모클래스로 묶어줄 수 있다. 

 

class Pet {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    eat() {  // extends의 원리는 eat을 먼저 자식요소인 Cat, Dog에서 찾고 없으면 부모요소인 Pet에서 eat을 찾아 출력한다.
        const { name } = this; // name객체를 this에서 추출해옴
        return `${name} is eating!` // this에서 추출해온 name을 사용한 return 
    }
}

class Cat extends Pet {
    constructor(name, age, livesLeft = 9) { // 만일 Cat 클래스에 추가 정보를 주고 싶을때, 이처럼 name, age가 부모 클래스 Pet과 중복되는 내용이면 super를 사용해서 생략이 가능하다.
        // this.name= name;
        // this.age = age;
        super(name, age);
        this.livesLeft = livesLeft;
    }
    meow() {
        return 'MEOWWW';
    }
}

class Dog extends Pet {
    bark() {
        return "WOOF!!";
    }
    eat() { // extends의 원래에 따라 eat을 먼저 자식요소에서 찾을때, eat이 있기때문에 자식요소의 eat을 출력해서 eating bug!!!!가 출력된다.
        return `${this.name} is eating bug!!!!`
    }
}

'The Web Developer 부트캠프 2022' 카테고리의 다른 글

Node.js 기본  (0) 2022.09.28
터미널 명령어  (0) 2022.09.28
JS 프로토타입과 클래스, new  (0) 2022.09.27
TV 프로그램 API 응용  (0) 2022.09.27
API AXIOS 이용한 TV 프로그램  (0) 2022.09.26