Javascript/프로토타입 & 클래스

ES6 Class + Class 상속 (Prototype을 쉽게 이용하기)

appmaster 2021. 2. 1. 13:27

class문법을 사용하면 상속을 해야하는상황에서 훨씬 더 쉽게 이용할 수 있습니다.

class Animal{
    constructor(type, name, sound){
        this.type = type;
        this.name = name;
        this.sound = sound;
    }

    say(){
        console.log(this.sound);
    }
}

class Dog extends Animal{
    constructor(type, name, sound){
        super(type, name, sound);
    }
}

class Cat extends Animal{
    constructor(name, sound){
        super('고양이', name, sound);
    }
}

const dog = new Dog('개', '멍멍이', '멍멍');
const cat = new Cat('야옹이', '야옹');

dog.say();
cat.say();

 

만약 상속받은 class에서 super라는 키워드를 이용하여 Animal 클래스가 가지고 있는 constructor를 먼저호출하고 난 후에 자식class에서 해야할일을 합니다.

'Javascript > 프로토타입 & 클래스' 카테고리의 다른 글

객체 생성자 상속하기 Prototype  (0) 2021.02.01
객체 생성자 Prototype  (0) 2021.02.01