▶️ class를 상속할때 쓰는 extends
class grandfather {
constructor(name, name2) {
this.성 = "Kim";
this.이름 = name;
this.이름2 = name2;
}
sayHello() {
console.log("안녕");
}
sayHi() {
console.log("안녕 저는 할아버지에요");
}
}
class father extends grandfather {
constructor(name, name2) {
super(name, name2);
this.age = 50;
}
sayHi() {
console.log("안녕 저는 아버지에요");
super.sayHi();
}
}
let myGranpa = new grandfather('최고','민수');
console.log(myGranpa);
myGranpa.sayHi();
- class안에 복사할 내용이 너무 많아지면 코드가 너무 길어지는데, 이를 방지하기 위해 활용할 수 있는 것이 extends 문법이다.
- super()는 'extends로 상속 중인 부모 class 의 constructor' 를 의미한다.
- this를 쓰기 전에 super()를 사용하지 않으면 에러를 출력한다. 즉 this를 쓰기 전에 super를 먼저 사용해야한다.
- new 함수에 파라미터를 넣지 않으면 인수를 넘겨받는 변수의 key값은 underfined로 출력된다.
▶️ 메서드를 실행시키는 과정
- f1 object에 메서드가 있는지 보고
- 없으면 father.prototype에 메서드가 있는지 보고
- 없으면 grandfather.prototype에 메서드가 있는지 본다.
- 이런 식으로 sayHello를 실행하기 위해 부모를 조사한다.