프로토타입 체인
extends
와 super
키워드를 이용해 상속을 구현할 수 있다.class Teacher extends Person {
constructor(first, last, age, gender, interests, subject, grade) {
this.name = {
first,
last
};
this.age = age;
this.gender = gender;
this.interests = interests;
// subject and grade are specific to Teacher
this.subject = subject;
this.grade = grade;
}
} //extends 키워드만 이용해서 상속을 표현 했을때
class Teacher extends Person {
constructor(first, last, age, gender, interests, subject, grade) {
super(first, last, age, gender, interests);
// subject and grade are specific to Teacher
this.subject = subject;
this.grade = grade;
}
} // super 키워드까지 이용해서 상속을 표현 했을때
let snape = new Teacher('Severus', 'Snape', 58, 'male', ['Potions'], 'Dark arts', 5);
snape.greeting(); // Hi! I'm Severus.
snape.farewell(); // Severus has left the building. Bye for now.
snape.age // 58
snape.subject; // Dark arts
MDN에서 메서드를 검색 했을 때 .prototype이 자주 등장하던 이유
이번 이틀간 학습기간 전 수많은?!(내 기준) 메서드를 검색 했을 때 많은 키워드에서 prototype이 자주 보여서 사용할 때 .prototype을 같이 써야하나 라는 고민을 했던 것 같다. 굳이 붙이지 않아도 메서드는 잘 실행됐다. 그래서 난 더 의문이 생겼다. 왜 써있을까?
과제를 진행하던 나는 나도 모르게 class를 생성했고
그 class의 부모인 Object에 내장 되어 있는 인스턴스 메서드를 상속받아서 사용 했던 것이었다.
이번 학습기간을 통해 완전히 분명해진 것은 아니지만 그래도 조금은 뚜렷해졌다.
let div = document.createElement('div');
div.__proto__
div.__proto__.__proto__
div.__proto__.__proto__.__proto__
div.__proto__.__proto__.__proto__.__proto__
div.__proto__.__proto__.__proto__.__proto__.__proto__
div.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__
div.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__
이 과정을 콘솔에 입력하면 더 명확해진다.
마지막 출력 값이 Object.prototype이 나오기 때문이다.
🔑 나는 그래서 이 프로토타입은
우리가 각 자식 클래스마다 메서드를 따로 쓰는 번거로움을 덜어주는 녀석이라고 이해했다.