class calCul{
constructor(name,first,second){
this.name = name;
this.first = first;
this.second = second;
}
sum(){
return `${this.name} : ` + (this.first + this.second);
}
}
let park = new calCul('park',10,20);
console.log(park.sum());
위 코드 내용을 살리고 추가적으로 더 함수 인자를 받거나 메소드를 만들고 싶다면 extends 로 calCul을 상속받아 새로운 class를 작성할 수 있다.
class calCul{
constructor(name,first,second){
this.name = name;
this.first = first;
this.second = second;
}
sum(){
return `${this.name} : ` + (this.first + this.second);
}
}
class newCalCul extends calCul{
constructor(name,first,second,third){
this.name = name;
this.first = first;
this.second = second;
this.third = third;
}
sum(){
return `${this.name} : ` + (this.first + this.second + this.third);
}
avg(){
return `${this.name} : ` + (this.first + this.second + this.third) / 3 ;
}
}
let park = new newCalCul('park',10,20,30);
위의 코드처럼 작성할 수 있지만 그럼 상속이란 의미가 사라진다. 이를 해결하기 위해 부모 클래스에서 가지고 있는 기능은 부모 클래스에서 작동하고 없는 기능은 자식 클래스에서 실행하도록 하기위한 것이 super이다.
class calCul{
constructor(name,first,second){
this.name = name;
this.first = first;
this.second = second;
}
sum(){
return (this.first + this.second);
}
}
class newCalCul extends calCul{
constructor(name,first,second,third){
super(name,first,second); //super뒤에 괄호가 붙으면 부모 클래스의 생성자이다
this.third = third;
}
sum(){
return `${this.name} : ` + (super.sum() + this.third);
}
avg(){
return `${this.name} : ` + (this.first + this.second + this.third) / 3 ;
}
}
let park = new newCalCul('park',10,20,30);
console.log(park.sum());
console.log(park.avg());
super(name,,first,,second)를 전달하게 되면 newCalCul의 부모 클래스인 calCul 클래스의 생성자가 호출이되고 생성자 안에서 프로퍼티들이 생겨나기때문에 자식 클래스에서는 this.third만을 실행하면 되는 것이다.
sum()의 코드도 부모 클래스에서 first와 second의 합을 실행하고 있기때문에 그 결과 값을 가져와서 자식 클래스에서 사용할 수 있다.
'Programming Languages > javascript' 카테고리의 다른 글
Callback (0) | 2020.01.15 |
---|---|
class (0) | 2020.01.04 |
prototype (0) | 2020.01.03 |