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.<변수>
의 형태로 어느 함수의 내부라도 접근할 수 있다.
개발을 진행하다 보면 기존에 작성된 클래스를 바탕으로 하되 일부 기능만 변경하거나 새롭게 추가하고 싶을 때가 있다. 이런 경우, 새로 생성한 클래스는 부모클래스로부터 상속을 받게 되며 이 때에는 받드시 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