[OOP] super 키워드

alirz-pixel·2022년 7월 18일

OOP

목록 보기
1/1

person 을 상속받은 PersonPlus

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

class PersonPlus extends Person {
    avg() {
        return this.sum() / 2;
    }
}

var kim = new PersonPlus('kim', 10, 20);
console.log("kim.sum()", kim.sum());
console.log("kim.avg()", kim.avg())

위와 같이 Person 클래스와 해당 클래스를 상속받는 PersonPlus 클래스가 있다고 하자.

PersonPlus 클래스에서는 현재 avg라는 함수를 추가로 작성하여 사용중이나, 이제는 third 까지 추가하여 사용해보고 싶다. 그러면 어떻게 작성해야 할까?

PersonPlus에 third 추가하기

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

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;
    }
}

var kim = new PersonPlus('kim', 10, 20, 30);
console.log("kim.sum()", kim.sum());
console.log("kim.avg()", kim.avg())

위와 같이 PersonPlus에 constructor을 새로 정의하여 사용할 수도 있다.
근데 위의 코드처럼 작성하게 될 경우, 상속을 쓸 이유가 전혀 없어진다. (PersonPlus에서 본인 클래스의 내용을 관리하고 있기 때문)

이럴 때, 우리는 부모 오브젝트의 함수를 호출할 때 사용하는 super 키워드를 사용할 수 있다.

super([arguments]) : 부모클래스의 생성자 호출
spuer.functionOnParent([arguments]) : 부모 오브젝트가 가진 함수 호출

super 키워드를 알게되었으니, 우리는 이제 위의 코드를 상속 쓸 이유가 생기도록 코드를 작성할 수 있게 되었다.

super 활용하기

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

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.sum() / 3;
    }
}

var kim = new PersonPlus('kim', 10, 20, 30);
console.log("kim.sum()", kim.sum());
console.log("kim.avg()", kim.avg())

위와 같이 super 키워드를 사용함으로써 우리는 부모 오브젝트의 생성자를 그대로 사용하고, 상속받은 클래스에서 새로 정의한 변수 또한 생성자를 통해 초기화 할 수 있게 되었다!

추가적으로 sum 함수 또한 (this.first + this.second + this.third)로 작성할 필요없이 부모 오브젝트에 있는 sum 함수를 호출함으로써 더 객체지향스럽게 작성할 수 있다. (super.sum() 사용)

reference

https://opentutorials.org/module/4047/24620
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/super

0개의 댓글