JS 프로토타입 키워드 (constructor, super, extends)

DaeHOON·2022년 11월 21일
0

constructor

constructor 메서드는 클래스의 인스턴스 객체를 생성하고 초기화하는 특별한 메서드이다.

super

super 키워드는 부모 오브젝트의 함수를 호출할 때 사용된다.
생성자에서는 super 키워드 하나만 사용되거나 this 키워드가 사용되기 전에 호출되어야 합니다. 또한 super 키워드는 부모 객체의 함수를 호출하는데 사용될 수 있다.

class Polygon {
  constructor(height, width) {
    this.name = 'Polygon';
    this.height = height;
    this.width = width;
  }
  sayName() {
    console.log('Hi, I am a ', this.name + '.');
  }
}

class Square extends Polygon {
  constructor(length) {
    this.height; // 참조오류가 발생합니다. super가 먼저 호출되어야 합니다.

    // 여기서, 부모클래스의 생성자함수를 호출하여 높이값을 넘겨줍니다.
    // Polygon의 길이와 높이를 넘겨줍니다.
    super(length, length);

    // 참고: 파생 클래스에서 super() 함수가 먼저 호출되어야
    // 'this' 키워드를 사용할 수 있습니다. 그렇지 않을 경우 참조오류가 발생합니다.
    this.name = 'Square';
  }

  get area() {
    return this.height * this.width;
  }

  set area(value) {
    this.area = value;
  }
}

extends

extends 키워드는 클래스를 다른 클래스의 자식으로 만들기 위해 class 선언 또는 class 식에 사용된다.
extends 키워드는 내장 객체뿐만 아니라 사용자 정의 클래스를 하위 클래스로 만들기 위해 사용될 수 있다.
확장( 클래스)의 .prototype은 Object 또는 null이어야 한다.

profile
프론트엔드 개발 velog

0개의 댓글