class의 extends와 super에 대해 알아본다.
역시 자바랑 똑같다.
class Parent {
constructor(name, age) {
this.name = name;
this.age = age;
}
};
이 class와 비슷한 class를 만들고싶다.
그냥 복붙해도 되지만, 코드 양을 줄이고 유지보수를 편하게 하기 위해 extends를 사용해 Parent class를 상속받아
편리하게 새로운 class를 구현할 수 있다.
class Child extends Parent {
};
이러면 Parent 안의 생성자가 Child에 똑같이 구현되어
Child를 new 해서 만들어지는 인스턴스들은 Parent class에 있는 name과 age라는 필드값을 갖는다.
하지만 한계가 있다.
Child class의 생성자에 Parent의 생성자에 없는 새로운 변수, 함수를 추가하고 싶다면
class Child extends Parent {
constructor(name, age, height) {
super(name, age);
this.height = height;
}
};
이렇게 Child안에 생성자를 만들고 그 안에 또 super()를 써줘야한다.
저렇게 super()를 안쓰고 바로 this 변수나 함수를 추가하면
이런 에러가 난다.
이 super()는 부모의 생성자와 일치한다.
즉, super에는 부모 class의 this.name = name;과 this.age = age;가 들어있다.
주의해야할 점은 부모 class의 생성자가 요구하는 인자를 자식 class도 물려받기때문에,
자식 class로 인스턴스를 만들 때 생성자에 부모 생성자가 요구하는 인자를 모두 넣어줘야한다.
그렇지않으면 자식 생성자든 부모 생성자든 입력받지않은 해당 값은 undefined로 정의된다.
그래서 자식 class로 인스턴스를 만들면...
const a = new Child('Jack', 27, 177);
이렇게 부모 클래스에서 요구되는 인자부터 자식 클래스가 요구하는 인자까지 전부 생성자에 넣어주면 된다.
class Parent {
constructor(name, age) {
this.name = name;
this.age = age;
}
gender = 'male';
sayHi() {
console.log(`Hi. I am Parent. My name is ${ this.name } and ${ this.age } years old.`)
}
};
constructor() 밖에 정의된 변수와 함수는 prototype이다.
만약...
class Child extends Parent {
constructor(name, age, height) {
super(name, age);
this.height = height;
}
sayGender() {
super.sayHi();
console.log(`I am ${this.gender}.`); --> super.gender가 아니네?
}
};
Child가 Parent를 extends하고 해당 class의 prototype에 sayGender라는 함수를 추가했다.
이렇게 자식 class의 prototype에서 함수를 만들 때 super.함수명(); 을 써주면 부모 class의 prototype에 있는
함수를 가져와 쓸 수 있다.
근데 class는 prototype영역에서 함수말고 변수를 지정하면 해당 변수가 prototype에 들어가는게 아니라
constructor() 안의 this 변수처럼 사용된다.
위 사진처럼 sayGender라는 함수만 prototype으로 들어가고 gender는 인스턴스를 호출할 때 constructor()에 작성한 다른 this 변수들과 함께 같이 불러져온다.
이 부분은 좀 더 알아보고 작성을 이어가겠다.