Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript super 키워드 완벽 정리: 부모 클래스에 접근하는 방법

super 키워드란?

super 키워드는 객체의 부모(parent)에 있는 속성이나 함수에 접근하고 호출할 때 사용됩니다. super.prop 또는 super[expr] 형태의 표현식은 클래스와 객체 리터럴의 모든 메서드 정의 내에서 유효하며, 특히 extends 키워드를 사용해 확장(상속)된 클래스에서 주로 활용됩니다.

기본 문법

super(arguments);

생성자 안에서 호출하면 부모 클래스의 생성자를 실행하고, 메서드 안에서 super.method() 형태로 호출하면 부모 클래스의 메서드를 실행할 수 있습니다.

예제 코드

다음 예제에서는 Person이라는 클래스의 특성을 Student라는 클래스로 확장했습니다. 두 클래스에는 각각 고유한 속성과 메서드가 정의되어 있습니다.

여기서 super 키워드는 부모 클래스(Person)의 속성과 메서드에 접근하기 위해 사용되고, 반면 this 키워드는 확장된 클래스(Student) 자신의 속성에 접근하는 데 사용됩니다.

<html>
<body>
<script>
    class Person {
        constructor(name, grade) {
            this.name = name;
            this.grade = grade;
        }
        goal() {
            return `${this.name} wants to become a crickter!`;
        }
        interest() {
            return `${this.name} interested in cricket !`;
        }
    }
    class Student extends Person {
        constructor(name, grade) {
            super(name, grade); // 부모 클래스 생성자 호출
        }
        need() {
            return `${this.name} needs a cricket kit`;
        }
        career() {
            return `${super.interest()}
            ${super.goal()}
            ${this.need()}`;
        }
    }
    const student = new Student('Rishab pant', '7');
    document.write(student.career());
</script>
</body>
</html>

코드 설명

  • Person 클래스: 이름(name)과 학년(grade)을 받아 저장하고, 목표(goal)와 관심사(interest)를 반환하는 메서드를 가집니다.
  • Student 클래스: extends Person으로 Person을 상속받으며, 생성자에서 super(name, grade)를 호출해 부모의 초기화 로직을 그대로 재사용합니다.
  • career() 메서드: super.interest()super.goal()로 부모의 메서드 결과를 가져오고, this.need()로 자식 클래스 자신의 메서드 결과를 함께 조합해 반환합니다.

실행 결과

Rishab pant interested in cricket !
Rishab pant wants to become a crickter!
Rishab pant needs a cricket kit

정리

super 키워드는 상속 구조에서 코드 중복을 줄이고 부모 클래스의 기능을 재사용할 수 있게 해주는 핵심 도구입니다. 생성자에서는 반드시 this를 사용하기 전에 super()를 먼저 호출해야 한다는 점도 기억해 두세요.