1. 생성자 (constructor) 함수

🔗 MDN 링크

클래스 내에서 생성자 함수는 하나만 있을 수 있습니다.
생성자 함수는 인스턴스 객체를 생성하고 초기화하는 특별한 메서드입니다.
생성자 함수를 작성하지 않으면, 기본 생성자(default constructor)가 제공되며,
기본(base) 클래스일 경우는 기본 생성자는 비어있으며, 파생(derived) 클래스일 경우 기본 생성자는 부모 생성자를 부릅니다.

MDN 예제

constructor 메서드 사용하기

class Square extends Polygon {
  constructor(length) {
    // length로 다각형의 넓이와 높이를 정의하기 위해 부모 클래스의 생성자를 호출합니다.
    super(length, length);
    // 참고: 파생 클래스에서, this를 사용하기 전에는 반드시 super()를 먼저 호출해야 합니다.
    // 그렇지 않으면 ReferenceError가 발생합니다.
    this.name = 'Square';
  }
  get area() {
    return this.height * this.width;
  }
  set area(value) {
    this.height = value ** 0.5;
    this.width = value ** 0.5;
  }
}

Using new on a class goes through the following steps:
1. (If it's a derived class) The constructor body before the super() call is evaluated. This part should not access this because it's not yet initialized.
2. (If it's a derived class) The super() call is evaluated, which initializes the parent class through the same process.
3. The current class's fields are initialized.
4. The constructor body after the super() call (or the entire body, if it's a base class) is evaluated.

Within the constructor body, you can access the object being created through this and access the class that is called with new through new.target. Note that methods (including getters and setters) and the prototype chain are already initialized on this before the constructor is executed, so you can even access methods of the subclass from the constructor of the superclass. However, if those methods use this, the this will not have been fully initialized yet. This means reading public fields of the derived class will result in undefined, while reading private fields will result in a TypeError.

2. extends & super

2-1. extends

🔗 MDN 링크

extends 키워드는 클래스를 다른 클래스의 자식으로 만들기 위해 class 선언 또는 class 식에 사용됩니다.

MDN 예제

내장 객체에 extends 사용하기

class myDate extends Date {
  constructor() {
    super();
  }
  getFormattedDate() {
    var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    return this.getDate() + "-" + months[this.getMonth()] + "-" + this.getFullYear();
  }
}

2-1. super

🔗 MDN 링크

super 키워드는 부모 클래스의 함수를 호출할 때 사용됩니다.
생성자 함수 내에서 쓰일 때는, super 키워드는 한번만 사용될 수 있습니다.
this 키워드가 사용되기 전에 사용되어야 하며, 그렇지 않을 경우 Reference 에러가 납니다.
생성자 함수 내에서 super를 호출하면 부모 클래스의 생성자 함수를 호출합니다.

📚 추가 학습

❕ 인터페이스에 대해 블로깅 하기
❕ #으로 은닉화 구현해보기
❕ getter, setter 학습 후 구현하기

profile
새싹 프론트엔드 개발자

0개의 댓글

Powered by GraphCDN, the GraphQL CDN