class Rabbit extends Animal {
}
이전글에서 상속클래스는 객체생성시 상위객체의 constructor를 자동으로 호출한다고 했다. 이부분에대해 보다 자세히 보자
명세서에 따르면, 클래스가 다른 클래스를 상속받고 constructor가 없는 경우엔 아래처럼 ‘비어있는’ constructor가 만들어지도록 규정되어있다.
아하...
class Rabbit extends Animal {
// 자체 생성자가 없는 클래스를 상속받으면 자동으로 만들어짐
constructor(...args) {
super(...args);
}
}
상위객체의 constructor가 자동으로 호출되는 것이 아니고 하위클래스에 constructor가 정의되어있지 않을때는 엔진이 constructor를 자동으로 정의한다는 것이다.
super(...args);로 상위 constructor를 호출한다.
그렇다면 사용자가 하위클래스에 constructor를 직접 정의해도 된다는 것이다. 하지만 정의하고 super(...args);를 추가하지 않으면 에러가 발생한다.
하위클래스에서 constructor를 구현하지 못한다면 말이 안되는 것으로 이러한 과정은 당연한 수순이다.
class Animal {
constructor(name) {
this.speed = 0;
this.name = name;
}
}
class Rabbit extends Animal {
constructor(name) {
this.ear = 2;
super(name);
}
}
new Rabbit()으로 rabbit객체가 만들어지고 ear프로퍼티가 추가되고 상위객체 constructor를 호출하여 speed,name 프로퍼티를 추가하면 되는것처럼 보인다. 그러나 에러가 발생한다.
하위constructor가 호출되면 하위클래스 빈객체가 생성되고 객체.super()로 상위constructor에서 프로퍼티가 추가된후 하위 constructor의 프로퍼티가 추가된다.
constructor(name) {
this.ear = 2;
super(name);
}
상위constructor가 완료된후 하위 constructor가 수행된다.
constructor(name) {
super(name);
this.ear = 2;
}
이와 같이 순서가 지켜져야 하는 것이다.