객체 지향 프로그래밍의 특성 중 상속을 JavaScript에서 구현할 때에는 프로토타입 체인을 사용
EX) DOM 엘리먼트는 innerHTML과 같은 속성, 또는 append()와 같은 메서드가 있습니다.
각각의 엘리먼트가 해당 메서드나 속성이 있다는 것을 통해
Element라는 공통의 부모가 있음을 알 수 있습니다.
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__ // null (Object)
ECMAScript 2015부터
C++나 Java와 유사한 클래스 문법 적용
하위 클래스는 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;
}
}
constructor()에서 처음에 super() 연산자를 정의하면 코드 읽기 쉬워짐
이는 상위 클래스의 생성자를 호출
super()의 매개변수를 통해
상위 클래스의 멤버를 상속받을 수 있음
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;
}
}