JavaScript Class Constructor를 알아보자

YHC·2022년 4월 14일
1
post-thumbnail

Constructor란


constructor 메서드는 클래스의 인스턴스 객체를 생성, 초기화하는 역할을 한다. 파이썬의 클래스에서 __init__ 으로 변수를 초기화하는 것과 동일한 역할을 한다고 이해하면 된다.

기본 형태


class Animal {
	
	// run, stop 메서드 호출에 앞서 name 객체의 생성과 초기화 수행
  constructor(name) {
    this.speed = 0;
    this.name = name;
  }
  run(speed) {
    this.speed = speed;
    alert(`${this.name} 은/는 속도 ${this.speed}로 달립니다.`);
  }
  stop() {
    this.speed = 0;
    alert(`${this.name} 이/가 멈췄습니다.`);
  }
}

let animal = new Animal("동물");

왜 쓸까?

constructor는 클래스 내부에서 혹은 다른 클래스에 상속한 경우, 해당 클래스 내부에서 사용하기 위한 객체를 정의하는 것이라고 볼 수 있다. 클래스 내부에 다양한 함수가 존재한다면 constructor로 생성, 초기화된 객체는 this.<변수>의 형태로 어느 함수의 내부라도 접근할 수 있다.


Constructor 활용


개발을 진행하다 보면 기존에 작성된 클래스를 바탕으로 하되 일부 기능만 변경하거나 새롭게 추가하고 싶을 때가 있다. 이런 경우, 새로 생성한 클래스는 부모클래스로부터 상속을 받게 되며 이 때에는 받드시 super()메소드를 통해 부모 클래스의 생성자를 호출해야 한다.

  • super() 메소드는 자식 클래스 생성자 내부에서만 사용할 수 있다.

예시

  • 부모클래스인 Animal을 상속 받은 Rabbit 클래스는 부모 클래스의 생성자를 상속받기 위해 super() 메소드를 사용한다.
class Animal {

  constructor(name) {
    this.speed = 0;
    this.name = name;
  }

  // ...
}

class Rabbit extends Animal {

  constructor(name, earLength) {
    super(name);
    this.earLength = earLength;
  }

  // ...
}

let rabbit = new Rabbit("흰 토끼", 10);
alert(rabbit.name); // 흰 토끼
alert(rabbit.earLength); // 10

참고

클래스 상속
constructor - JavaScript | MDN

profile
배워서 나도쓰고, 남도 주고

0개의 댓글