🪁react/바닐라 js 실습

클래스 컴포넌트 super란?

하얀성 2024. 4. 3. 16:50

super()는 자식 생성자 안에 쓰여서 부모 생성자를 자식 안에서 호출하여 그 안의 내용을 쓸 수 있도록 한다.

 

 

아래 예시를 보면 qs(querySelector)임의 지정함수를 통해 index.js에서 요소를 불러옴.

SearchFromView.js를 보게되면 아래에 느닷없이 element.js가 나오게 되는데

 

모두 super를 통해서 부모 클래스 View 생성자를 호출해서

그 매개변수(element)로 qs로 호출한 태그요소(<form></form>)를 element 변수 안에 저장해서 생성자를 불러온 것.

 

마치 jsx의 app.jsx에서 컴포넌트들을 세트로 데려올 때 상속에 상속을... 데이터를 props훅으로 전달하는 것과 비슷한 과정으로 여겨진다.

 

요약하면, super 호출은 상속받은 클래스의 생성자를 실행하는 데 사용되며, 부모 클래스의 메서드를 호출할 때에도 super 키워드를 사용할 수 있습니다. 이러한 방식으로 클래스 간의 상속 관계에서 초기화 및 메서드 재사용이 이루어집니다.

super.메소드 이렇게 오버라이드(재정의)해서 상속받은 메서드를 불러오는게 정석이다.


index.js

<form id="search-form-view">
        <input type="text" placeholder="검색어를 입력하세요" autofocus />
        <button type="reset" class="btn-reset"></button>
      </form>

View.js

export default class View {
  constructor(element) {
    console.log(tag, "constructor");

    if (!element) throw "no element";

    this.element = element;
    this.originalDisplay = this.element.style.dispaly || "";

    return this;
  }
}

SearchFromView.js

const tag = "[SearchFormView]";

export default class SearchFormView extends View {
  constructor() {
    console.log(tag, "constructor");

    super(qs("#search-form-view"));

    this.resetElement = qs("[type=reset]", this.element);

    this.showResetButton(false);
  
  }

  showResetButton(visible = true) {
    this.resetElement.style.display = visible ? "block" : "none";
  }
}