나만의 정의: 선언된 class를 자식에게 상속하는 방법
어떻게? super
와 extends
를 쓴다.
// 이미 선언된 Person 객체
class Person {
// constructor라는 생성자
constructor(first, last, age, gender, interests) {
this.name = {
first,
last
};
this.age = age;
this.gender = gender;
this.interests = interests;
}
greeting() {
console.log(`Hi! I'm ${this.name.first}`);
};
farewell() {
console.log(`${this.name.first} has left the building. Bye for now!`);
};
}
// 위의 Person에서 Teacher로 상속 -> extends를 통해서
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;
}
}
// 더 간펀한 방법
class Teacher extends Person {
constructor(subject, grade) { // constructor 안에는 추가하고 싶은 인자만 입력
super(); // 괄호를 빈칸으로 만듦으로써 부보class 모든 것을 가지고 옴
// subject and grade are specific to Teacher
this.subject = subject;
this.grade = grade;
}
}
DOM의 요소도 JS와 같이 부모 요소 및 prototype이 있음을 아래와 같이 확인할 수 있음
let div = document.createElement('div');
div.__proto__ //HTMLDivElement
/* HTMLDivElement.prototype -> 출력: HTML class의 청사진을 가지고 있는 prototype 확인 가능*/
div.__proto__.__proto__ // HTMLElement
div.__proto__.__proto__.__proto__ // Element
div.__proto__.__proto__.__proto__.__proto__ // Node
div.__proto__.__proto__.__proto__.__proto__.__proto__ // EventTarget