class #2

김세주·2021년 1월 20일
0

JavaScript

목록 보기
5/12

Inheritance (상속)

만약

class Person{
    constructor(name, first, second){
        this.name=name;
        this.first=first;
        this.second = second;
    }
    sum(){
        return 'prototype : ' +(this.first +this.second);
    }
}

이 코드에 sum말고 다른 기능 함수들을 추가하고싶다면?
-> 일일이 함수를 추가해도 되지만, 클래스가 무거워진다. 원본 클래스 코드를 바꾸기도 부담스럽다.
--> 새로운 클래스를 만들어주자.

class PersonPlus{
    constructor(name, first, second){
        this.name=name;
        this.first=first;
        this.second = second;
    }
    sum(){
        return 'prototype : ' +(this.first +this.second);
    }
    avg() {
        return (this.first +this.second)/2;
    }
}

중복을 뺴주자. 상속을 이용

class PersonPlus extends Person{
PersonPlus라는 객체는 Plus를 상속한다. Person을 확장한다.

중복되는 코드 지우면 된다.

class PersonPlus extends Person{
    
    avg() {
        return (this.first +this.second)/2;
    }
}

유지보수의 편의성을 도모할 수 있게 된다.
상속은 코드의 양을 줄여주고, 부모 클래스의 속성을 그대로 extends를 사용해 상속한다. 자식클래스는 부모가 없는 코드를 추가하여 필요에 따라 호출, 메소드를 사용할 수 있다.

super

클래스와 부모 클래스 간의 관계.

class Person{
    constructor(name, first, second){
        this.name=name;
        this.first=first;
        this.second = second;
    }
    sum(){
        return 'prototype : ' +(this.first +this.second);
    }
}
class PersonPlus extends Person{
    
    avg() {
        return (this.first +this.second)/2;
    }
}

let kim = new Person('kim',10,20);

이 코드에서 아쉬운 점이 있다.
바로 마지막 줄 new Person('kim', 10, 20)에 새로운 세번째 값 을 넣어주고 싶다.
new Person('kim',10,20,30);
그러면 이렇게 처리해주면된다.

class PersonPlus extends Person{
    constructor(name, first, second, third){
        this.name=name;
        this.first=first;
        this.second = second;
        this.third = third
    }
    sum(){
        return this.first +this.second + this.third;
    }
    avg() {
        return (this.first +this.second+ this.third)/3;
    }
}

그러나 이것은 원점으로 돌아온것. 상속을 쓴 의미가없다.

부모 클래스한테 일을 시키고 부모 클래스가 못하는 일은 나만 하는 키워드 super
super에 괄호가 없다면 그것은 부모클래스 자체, super()라면 부모클래스의 생성자이다.

class PersonPlus extends Person{
    constructor(name, first, second, third){

        super(name, first, second) //부모에서가져옴

        this.third = third
    }
    sum(){
        return super.sum() + this.third;
    }
    avg() {
        return (this.first +this.second+ this.third)/3;
    }
}

이렇게 super을 통해 중복을 줄일 수 있다.

profile
시간은 내 편이다.

0개의 댓글