Inheritance : 상속

wonyoung·2024년 1월 30일

Javascript

목록 보기
7/36

상속은 객체들 간의 관계를 구축하는 방법이다. 수퍼클래스, 또는 부모 클래스 등의 기존의 클래스로 부터 속성과 동작을 상속받을 수 있다.

class Model {
    name;
    year;

    constructor(name, year) {
        this.name = name;
        this.year = year;
    }
}

class femaleModel extends Model { // 상속할 때는 extends 키워드 사용합니다.
    dance() {
        return `${this.name}이 춤을 춥니다.`
    }
}
class maleModel extends Model {
    sing() {
        return `${this.name}이 노래를 합니다.`
    }
}
const wonYoung = new femaleModel('이원영', 1997)
console.log(wonYoung.dance())

const jiTak = new maleModel('한지탁', 1998)
console.log(jiTak.sing())


// 아래 경우 true 반환
console.log(wonYoung instanceof Model)
console.log(wonYoung instanceof femaleModel)

console.log(jiTak instanceof Model)
console.log(jiTak instanceof maleModel)

// 아래 경우 flase 반환
console.log(wonYoung instanceof maleModel)
console.log(jiTak instanceof femaleModel)

부모는 자식에게 상속받지 못한다.

  • instanceof 연산자
    instanceof 연산자를 사용하면 객체가 특정 클래스에 속하는지 아닌지를 확인할 수 있습니다. 또한, 상속 관계도 확인해줍니다.

강의출처 https://youtu.be/ZOVG7_41kJE?si=Gao3ZNE0CzZhpRFv

profile
😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀😀

0개의 댓글