자바스크립트 super 제대로 이해하기

남양주개발자

·

2022. 1. 10. 07:30

728x90
반응형

자바스크립트 super 제대로 이해하기

super 키워드는 상위(부모) 객체의 함수를 호출할 때 사용됩니다.

문법

super([arguments]); // 부모 생성자 호출
super.functionOnParent([arguments]);

설명

클래스의 생성자(constructor)에서는 super 키워드 하나만 사용되거나 this 키워드가 사용되기 전에 호출되어야 합니다. 또한 super 키워드는 부모 객체의 함수를 호출하는데 사용될 수 있습니다.

클래스에서 super 사용하는 방법

class Parent {
  constructor(age) {
    this.name = "parent";
    this.age = age;
  }

  sayMyName() {
    console.log(this.name);
  }
}

class Child extends Parent {
  constructor(age) {
    super(age);
    this.name = "child";
  }
}

const child = new Child(10);

child.sayMyName(); // child

this 키워드가 사용되기 전에 호출할 경우

클래스 생성자(constructor)에서 this 키워드를 사용하기 전에 super를 호출하지 않으면 아래와 같은 참조오류(ReferenceError)가 발생합니다.

class Child extends Parent {
  constructor(value) {
    // super 누락!
    // 참조오류가 발생합니다. super가 먼저 호출되어야 합니다.
    console.log(this);
  }
}
ReferenceError
this hasn't been initialised - super() hasn't been called

static 메서드에서 super 호출

static 메서드에서도 super를 호출할 수 있습니다.

class Parent {
  constructor(age) {
    this.name = "parent";
    this.age = age;
  }

  sayMyName() {
    console.log(this.name);
  }

  static holy() {
    return "holy";
  }
}

class Child extends Parent {
  constructor(age) {
    super(age);
    this.name = "child";
  }

  static holymoly() {
    console.log(super.holy() + "moly!");
  }
}

Child.holymoly(); // holymoly!
728x90
반응형
그리드형

💖 저자에게 암호화폐로 후원하기 💖

아이콘을 클릭하면 지갑 주소가자동으로 복사됩니다