JavaScript_객체지향 키워드

Eugenius1st·2022년 7월 25일
1

JavaScript

목록 보기
25/62

JavaScript_객체지향 키워드

Constructor

Constructor매서드는 클래스의 인스턴스 객체를 생성하고 초기화 하는 매서드

class Polygon {
  constructor() {
    this.name = 'Polygon';
  }
}

const poly1 = new Polygon();

console.log(poly1.name);
// expected output: "Polygon"

구문

constructor() { ... }
constructor(argument0) { ... }
constructor(argument0, argument1) { ... }
constructor(argument0, argument1, ... , argumentN) { ... }

Constructor를 사용하면 다른 모든 메서드 호출보다 앞선 시점인, 인스턴스 객체를 초기화 할 때 수행할 ㅊ기화 코드를 정의 할 수 있다.

class Person {
  constructor(name) {
    this.name = name;
  }
  introduce() {
    console.log(`Hello, my name is ${this.name}`);
  }
}
const otto = new Person('Otto');

otto.introduce();

클래스에 생서자를 정의하지 않으면 기본 생성자를 사용한다.
아무것도 상속하지 않는 기본 클래스 일 때 기본 생성자는 빈 매서드이다.

constructor() {}

다른 크래스를 상속하는 경우, 기본 생성자는 자신의 매개 변수를 부모 크래스의 생성자로 전달한다.

constructor(...args) {
  super(...args);
}

따라서 다음과 같은 코드를 작성할 수 있다.

class ValidationError extends Error {

  printCustomerMessage() {
    return `Validation failed :-( (details: ${this.message})`;
  }

}

try {
  throw new ValidationError("Not a valid phone number");
} catch (error) {
   if (error instanceof ValidationError) {
    console.log(error.name); // ValidationError가 아니라 Error!
    console.log(error.printCustomerMessage());
  } else {
    console.log('Unknown error', error);
    throw error;
  }
}

``VaildationError```클래스는 아무런 초기화 동작도 필요하지 않으므로 생성자를 별도로 명시하지 않았으며, 대신 기본 생성자가 매개변수로 부모 Error 클래스의 초기화를 처리하고 있다.

그러나, 파생 클래스에 직접 생성자를 정의할 경우, 부모 클래스의 생성자를 호출하려면 직접
super()를 호출해야 한다.

class ValidationError extends Error {
  printCustomerMessage() {
    return `Validation failed :-( (details: ${this.message})`;
  }
}

try {
  throw new ValidationError("Not a valid phone number");
} catch (error) {
   if (error instanceof ValidationError) {
    console.log(error.name); // ValidationError가 아니라 Error!
    console.log(error.printCustomerMessage());
  } else {
    console.log('Unknown error', error);
    throw error;
  }
}

prototype 접근




profile
최강 프론트엔드 개발자가 되고싶은 안유진 입니다

0개의 댓글