JavaScript: Class 상속

MARCOIN·2022년 6월 3일
0

개인적인 공부 기록

목록 보기
11/11

개인적인 학습 기록용으로 자세한 설명 등은 포함되지 않았습니다. 혹 검색으로 유입된 경우 다른 문서를 참고하세요~!


1. 상속

: 상위 클래스의 기능을 하위 클래스에게 물려줌

class Student {
    constructor(name, email){
        this.name = name;
        this.email = email;
    }

    print_info(){
        console.log(`${this.name}의 이메일은 ${this.email} 입니다.`)
    }
}

class Professor extends Student {
    constructor(name, email, subject){
        super(name, email); // super 메소드 사용으로 부모 프로퍼티 사용
        this.subject = subject;
    }

    print_subject(){
        console.log(`${this.name} 교수의 과목은 ${this.subject}입니다.`)
    }
}


const user1 = new Student('Harry', 'harry@horgwarts.com');
user1.print_info();
// Harry의 이메일은 harry@horgwarts.com 입니다.
const user2 = new Professor('Severus Snape', 'severus@horgwarts.com', 'potion');
user2.print_info();
user2.print_subject();
// Severus Snape의 이메일은 severus@horgwarts.com 입니다.
// Severus Snape 교수의 과목은 potion입니다.

2. Method overriding

class Student {
    constructor(name, email){
        this.name = name;
        this.email = email;
    }

    print_info(){
        console.log(`${this.name}의 이메일은 ${this.email} 입니다.`)
    }
}

class Professor extends Student {
    constructor(name, email, subject){
        super(name, email); 
        this.subject = subject;
    }

    print_info(){
        console.log(`${this.name}의 이메일은 ${this.email} 입니다.`);
        console.log(`${this.name}의 담당과목은 ${this.subject} 입니다.`);
    }
}


const user1 = new Student('Harry', 'harry@horgwarts.com');
user1.print_info();
// Harry의 이메일은 harry@horgwarts.com 입니다.

const user2 = new Professor('Severus Snape', 'severus@horgwarts.com', 'potion');
user2.print_info();
// Severus Snape의 이메일은 severus@horgwarts.com 입니다.
// Severus Snape의 담당과목은 potion 입니다.

3. Method overriding (super 사용)

class Student {
    constructor(name, email){
        this.name = name;
        this.email = email;
    }

    print_info(){
        console.log(`${this.name}의 이메일은 ${this.email} 입니다.`)
    }
}

class Professor extends Student {
    constructor(name, email, subject){
        super(name, email); 
        this.subject = subject;
    }

    print_info(){
        super.print_info();
        console.log(`${this.name}의 담당과목은 ${this.subject} 입니다.`);
    }
}


const user1 = new Student('Harry', 'harry@horgwarts.com');
user1.print_info();
// Harry의 이메일은 harry@horgwarts.com 입니다.

const user2 = new Professor('Severus Snape', 'severus@horgwarts.com', 'potion');
user2.print_info();
// Severus Snape의 이메일은 severus@horgwarts.com 입니다.
// Severus Snape의 담당과목은 potion 입니다.
profile
공부하는 기획자 👀

0개의 댓글