
__proto__링크를 따라 부모 객체의 property나 method에 접근하는 것.
Prototype Chain을 통해 JavaScript에서 부모클래스에 대한 속성이나 메소드를 상속받을 수 있다.
class Person {
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}`);
};
}
이름, 나이, 성별, 관심사를 속성으로 가지는 Person 클래스를 정의했다.
그리고, Student라는 클래스를 추가로 정의하고 싶을 때, 학생의 경우 사람에 포함되어 있기 때문에 Person의 속성을 모두 가진다.
이럴 때, 상속의 개념을 사용하게 된다.
// class 규모가 작을때
class Student extends Person {
constructor(first, last, age, gender, interests, subject, grade){
super(first, last, age, gender, interests);
this.subject = subject;
this.grade = grade;
}
}
// class규모가 클 때
class Student extends Person {
constructor(first, last, age, gender, interests, subject, grade){
super(); // 자식클래스가 많아 속성이 여러개라면 다 써주기 너무 힘들다.
this.first = first;
this.last = last;
...
this.subject = subject;
this.grade = grade;
}
}
extends 키워드를 통해 상속받을 부모클래스를 설정하고, super 키워드를 통해 부모클래스의 속성을 정의할 수 있다.
consturctor에 초기값을 설정해주고 싶을 때
class Student extends Person {
constructor(first = 'kim', last = 'coding', ..., grade = 4){
super();
this.first = first; // Student클래스를 통한 인스턴스는 초기값을 따른다.
this.last = last;
...
this.subject = subject;
this.grade = grade;
}
}
상속과 프로토타입은 위의 내용처럼 특별히 지정해주지 않아도, 우리는 자연스럽게 자주 상속된 메소드를 사용하고 있다.
DOM을 이용할 때도 마찬가지이다.
let div = document.createElement('div');
우리가 새로운 HTML요소를 만들 때 사용하는 메소드 createElement를 통해 만들어진 div는 확인해보면
HTMLDivElement라는 클래스의 인스턴스이다.
위에서 __proto__ 링크를 통해 부모 클래스를 확인할 수 있다고 했다.
이를 활용해서 createElement 메소드의 상속관계가 어떻게 되어있는지 확인해보면,
div.__proto__ // HTMLDivElement
div.__proto__.__proto__ // HTMLElement
div.__proto__.__proto__.__proto__ // Element
div.__proto__.__proto__.__proto__.__proto__ // Node
div.__proto__.__proto__.__proto__.__proto__.__proto__ // EventTarget
div.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__ // Object
div.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__ // null

위의 형태처럼 최상위 클래스인 Object까지 상속관계가 형성되어 있다는 것을 알 수 있다.
모든 클래스의 가장 최상위 클래스(조상)는 Object임을 인지해놓자.