프론트엔드/Javascript
[Javascript] 자바스크립트 클래스 상속에서 super의 두가지 의미
jinwanseo
2021. 6. 9. 23:30
728x90
[Javascript / 자바스크립트] 객체지향 (클래스 / Class) 상속에서 super의 두가지 의미

1. 자식 클래스 내에서 부모클래스의 생성자 역할
2. 자식 클래스에서 부모 클래스의 메소드 접근 역할
기본 형태
class 부모클래스 {
constructor(변수1,변수2){
this.변수1 = 변수1;
this.변수2 = 변수2;
}
메소드(){
//기능
...
}
}
class 자식클래스 extends 부모클래스 {
constructor(변수1, 변수2, 변수3){
//super키워드로 부모클래스 생성자 호출
super(변수1,변수2);
this.변수3 = 변수3;
}
메소드2(){
//부모 클래스의 메소드 호출
super.메소드();
//추가할 자식 클래스만의 기능
...
}
}
샘플 예제
//부모 클래스
class Score {
constructor(math,english,korean){
this.math = math;
this.english = english;
this.korean = korean;
}
sum() {
return this.math + this.english + this.korean;
}
avg(){
const sum = this.sum();
console.log('평균 점수 (3과목) : '+ sum / 3);
}
}
//자식 클래스
class Student extends Score {
constructor(math,english,korean,science){
//super키워드를 통해 부모 클래스 생성자 호출
super(math,english,korean);
//추가 프로퍼티 초기화
this.science = science;
}
avg(){
//super.sum()을 통해 부모 클래스의
//메소드 접근
const sum = super.sum() + this.science;
console.log('평균 점수 (4과목): '+ sum / 4);
}
}
const stu = new Student(90,90,100,100);
stu.avg();
실행 결과
평균 점수 (4과목): 95
728x90