자바스크립트 객체 고급 - 상속

Deong_gu·2022년 3월 28일
0
post-thumbnail
post-custom-banner

클래스와 상속

//클래스
class PersonInformation{
    constructor(IQ, hobby, favoriteColor, weight, height, e_mail, score, penalty){
        this.IQ = IQ;
        this.hobby = hobby;
        this.favoriteColor = favoriteColor;
        this.weight = weight;
        this.height = height;
        this.e_mail = e_mail;
        this.score = score;
        this.penalty = penalty;
    }
    testresult(){
        return this.score - this.penalty;
    }
}
//상속
class PersonInformationPlus extends PersonInformation{
    constructor(IQ, hobby, favoriteColor, weight, height, e_mail, score, penalty, plusScore){
    super(IQ, hobby, favoriteColor, weight, height, e_mail, score, penalty);
    this.plusScore = plusScore;
    }
    testresult() {return super.testresult() + this.plusScore }
    e_mailId() {return this.e_mail.split('@')[0]}
}
const devil = new PersonInformationPlus(300,'trouble','red','none','none','devil@hell.devil',80,0,5);
console.log(devil);
console.log('devil.testresult : ', devil.testresult());//devil.testresult :  85
console.log(devil.e_mailId());//devil

__proto__ 또는 Object.create를 이용해 생성자를 통한 상속

//객체 생성
const jyo = {
    IQ: 120,
    score: 90,
    penalty: 10,
    plusScore: 3,
    testResult: function(){
        return this.score - this.penalty + this.plusScore;
    }
}
const jung = {
    IQ: 130,
    score: 95,
    penalty: 8,
    plusScore: 5,
}
//상속 (__proto__, Object.create())
jung.__proto__ = jyo;
const Ann = Object.create(jyo);
Ann.IQ = 140;
Ann.score = 100;
Ann.penalty = 5;
Ann.plusScore = 10;
console.log(jung.testResult());//92
console.log(Ann.testResult());//105
profile
큰 것을 작게, 작은 것을 구체적이게, 개발자답게
post-custom-banner

0개의 댓글