๋ฐ์ํ
class Person{
constructor(name, first, second){
this.name = name;
this.first = first;
this.second = second;
}
sum() {
return this.first + this.second;
}
}
class PersonPlus extends Person{
avg() {
return (this.first + this.second) / 2;
}
}
const kim = new PersonPlus('kim', 10, 20);
console.log('kim.sum()',kim.sum());
console.log('kim.avg()',kim.avg());
// ์ถ๋ ฅ๊ฐ
kim.sum() 30
kim.avg() 15
๐ ์ ์ฝ๋์์ PersonPlus๋ผ๊ณ ํ๋ ํด๋์ค์์ 'kim', 10, 20 ์ธ์ 30์ด๋ผ๋ ๊ฐ๋ ์ถ๊ฐ์ ์ผ๋ก ๊ฐ์ง๊ณ ์ถ๋ค๋ฉด???
class Person{
constructor(name, first, second){
this.name = name;
this.first = first;
this.second = second;
}
sum() {
return this.first + this.second;
}
}
class PersonPlus extends Person{
constructor(name, first, second, third){
this.name = name;
this.first = first;
this.second = second;
this.third = third;
}
sum() {
return this.first + this.second + this.third;
}
avg() {
return (this.first + this.second + this.third) / 3;
}
}
const kim = new PersonPlus('kim', 10, 20, 30);
console.log('kim.sum()',kim.sum());
console.log('kim.avg()',kim.avg());
โฅ ์ด๋ ๊ฒ ์ฐ๋๋??? NO!!
์์ด ๋๋ฌด ๊ธธ์ด์ง๊ณ , ์์์ด๋ผ๋ ๊ฐ๋ ์ด ๋ฌด์ํด์ง๋ค.
ํด๊ฒฐ๋ฐฉ๋ฒ => super
๋ถ๋ชจ ํด๋์ค๋ฅผ ๋ถ๋ฌ์ ๋ถ๋ชจ ํด๋์ค์๊ฒ ์ผ์ ์ํค๊ณ , ๋ถ๋ชจ๊ฐ ํ์ง ๋ชปํ๋ ์ผ์ ๋ด๊ฐ ํ๊ธฐ!
super๋ฅผ ์ฐ๋ฉด ๋ ๊ฐ๊ฒฐํ๊ฒ ์ฝ๋๋ฅผ ์์ฑํ ์ ์๋ค๋ ์ฅ์ ์ด ์๊ณ , ๋ค๋ฅธ ์ฌ๋์ด ๋ณด๊ธฐ์ ๋ ๊น๋ํด์ ธ์ ์ ์ง ๋ณด์ํ๊ธฐ ์ข์์ง๋ค.
super ์ ๋๊ฐ์ง ์ฉ๋ฒ
super๋ค์ ๊ดํธ()๊ฐ ๋ถ์ผ๋ฉด ๋ถ๋ชจ ํด๋์ค์ ์์ฑ์์ด๋ค.
super ๋ค์ ์ .์ด ๋ถ์ผ๋ฉด ๋ถ๋ชจ ํด๋์ค๋ฅผ ํตํด ๋ฉ์๋๋ฅผ ๋ถ๋ฌ์จ๋ค.
class Person{
constructor(name, first, second){
this.name = name;
this.first = first;
this.second = second;
}
sum() {
return this.first + this.second;
}
}
class PersonPlus extends Person{
constructor(name, first, second, third){
super(name, first, second);
this.third = third;
}
sum() {
return super.sum() + this.third;
}
avg() {
return (this.first + this.second + this.third) / 3;
}
}
const kim = new PersonPlus('kim', 10, 20, 30);
console.log('kim.sum()',kim.sum());
console.log('kim.avg()',kim.avg());
// ์ถ๋ ฅ๊ฐ
kim.sum() 60
kim.avg() 20
๋ฐ์ํ