[웹 개발 기초 자바스크립트] 14. super()

Shy·2023년 8월 31일
0

NodeJS(Express&Next.js)

목록 보기
16/39

Super

JavaScript에서 super 키워드는 객체의 부모에게 접근할 수 있는 메커니즘을 제공합니다. super는 클래스 내부에서 주로 사용되며, 다음 두 가지 주요 상황에서 사용된다.

  • Constructor 내에서: 자식 클래스의 생성자(constructor)에서 super()를 호출하면, 부모 클래스의 생성자가 실행된다. 이 호출은 항상 자식 클래스 생성자의 첫 번째 라인에서 이루어져야 하며, 이렇게 해야만 this 키워드를 사용할 수 있다.
class Parent {
  constructor(name) {
    this.name = name;
  }
}

class Child extends Parent {
  constructor(name, age) {
    super(name);  // 부모 클래스의 constructor 호출
    this.age = age;
  }
  • Method에서: super 키워드를 사용하여 부모 클래스의 메서드를 호출할 수 있다. 이는 메서드 오버라이딩(재정의) 상황에서 유용하게 사용된다.
class Parent {
  greet() {
    console.log("Hello from Parent");
  }
}

class Child extends Parent {
  greet() {
    super.greet();  // 부모 클래스의 greet 메서드 호출
    console.log("Hello from Child");
  }
}

const child = new Child();
child.greet();
// 출력:
// Hello from Parent
// Hello from Child

Constructor

constructor(생성자)를 사용하면 인스턴스화된 객체에서 다른 메서드를 호출하기 전에 수행해야 하는 사용자 지정 초기화를 제공할 수 있다.

클래스를 new를 붙여서 (new User("John"))인스턴스 객체로 생성하면 넘겨받은 인수와 함께 constructor가 먼저 실행된다.

이 떄 넘겨받은 인수인 John이 this.name에 할당된다.

class User {
  
  constructor(name) {
    this.name = name;
  }
  
  sayHi() {
    alert(this.name);
  }
  
}

let user = new User("John");
user.sayHi();

자바스크립트에서 super

  • super키워드는 자식 클래스 내에서 부모 클래스의 생성자를 호출할 때 사용된다.
  • super키워드는 자식 클래스 내에서 부모 클래스의 메소드를 호출할 때 사용된다.
class Car {
  constructor(brand) {
    this.carname = brand;
  }// 생성자
  present() {
    return `I have a ` + this.carname;
  }// 메소드
  
}

class Model extends Car {
  constructor(brand, mod) {
    super(brand);
    this.model = mod;
  }
  show() {
    return super.present() + `, it is a ` + this.model;
  }
}

let mycar = new Model("Ford", "Mustang");
mycar.show();
profile
초보개발자. 백엔드 지망. 2024년 9월 취업 예정

0개의 댓글