선결론 : super()를 이용하면 편리하지만 인터넷 익스플로어와는 호환성 문제가 있다.
클래스를 만들면 거기에 속한 속성들을 이용해서 다른 클래스에게 속성을 상속시킬 수 있다.
이 글에서는 ES6 문법을 이용해 class를 만들어 super로 상속하는 방법에 대한 내용이다.
class Polygon {
constructor(height, width) {
this.name = 'Polygon';
this.height = height;
this.width = width;
}
sayName() {
console.log('Hi, I am a ', this.name + '.');
}
}
위와 같은 코드를 상속받는 다른 class를 작성할 때에 super를 이용해 상위 class의 속성들을 받을 수 있다.
class Square extends Polygon {
constructor(height) {
this.height; // 참조오류가 발생합니다. super가 먼저 호출되어야 합니다.
// 여기서, 부모클래스의 생성자함수를 호출하여 높이값을 넘겨줍니다.
// Polygon의 길이와 높이를 넘겨줍니다.
super(height, width);
// 참고: 파생 클래스에서 super() 함수가 먼저 호출되어야
// 'this' 키워드를 사용할 수 있습니다. 그렇지 않을 경우 참조오류가 발생합니다.
this.name = 'Square';
}
get area() {
return this.height * this.width;
}
set area(value) {
this.area = value;
}
}
위처럼 super 안에 상속 받고 싶은 변수들을 정해 놓으면 상속을 받을 수가 있다.
다만 한 가지 주의해야 할 점은 인터넷 익스플로러와 호환이 전혀 안된다는 것이다.
아래 MDN 링크에는 정적 메소드나 객체 리터럴 등에서 사용되는 부분에 대한 설명이 더 잘 되어있다.
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/super
super
super 키워드는 부모 오브젝트의 함수를 호출할 때 사용됩니다.
developer.mozilla.org
'Programming Languages > Javascript' 카테고리의 다른 글
this의 세계 (0) | 2022.05.30 |
---|---|
비동기적 호출 - [setTimeout, setInterval] (0) | 2022.05.30 |
Javascript의 Class 활용법 (0) | 2022.05.30 |
Const, Var, Let (0) | 2022.05.30 |
Switch Cases (0) | 2022.05.30 |