JavaScript는 Prototype 기반 언어이다. 즉, JavaScript는 상속을 구현하기 위해 Prototype이라는 방식을 사용하며 여기서 Prototype은 원형 객체를 의미한다.
상속 관점에서, JavaScript의 유일한 생성자는 객체(Object) 뿐이다. 이때 각각의 객체는 모두 Prototype이라는 속성 을 지니고 있고 이는 해당 객체의 원형 객체 를 가리킨다.
Prototype을 통해 조회한 원형 객체에는 또 다른 원형 객체가 존재하고, 이러한 흐름이 반복되다가 원형 객체가 존재하지 않는 객체의 Prototype은 null이 되며 종료 된다.
이처럼, 하위 객체에서 상위 객체의 탐색은 Prototype을 통해 이루어지며, 이를 Prototype-Chain 이라고 부른다.
즉, Porototype-Chain은 Prototype을 통해 상위 객체를 조회하고 더 이상 상위의 객체가 존재하지 않을 경우 null 값을 가지게 된다. 이는 Prototype의 종점을 의미한다.
Human 클래스와 Student 클래스를 통한 예시
이때, 상속되는 속성 혹은 메서드는 prototype이라는 속성에 담겨있다.
class Human {
constructor (gender, age) {
this.gender = gender;
this.age = age;
}
eat() {
console.log('먹습니다.');
}
sleep() {
console.log('잡니다.');
}
}
class Student extends Human {
constructor (gender, age, grade) {
super(gender, age);
this.grade = grade;
}
info() {
console.log(`grade는 ${this.grade} 입니다.'`);
}
}
const man1 = new Student('m', 18, 3);
man1.__proto__; // Human { ... }
man1.eat(); // = man1.__proto__.eat()의 방식으로 동작한다.
man1.__proto__.eat(); // 동작한다.
man1.__proto__.__proto__ // Human의 constructor
man1.__proto__.__proto__.__proto__ // 유일한 생성자 object
man1.__proto__.__proto__.__proto__.__proto__ // null 종점
Reference
Mdn_상속과 프로토타입
Mdn_Object prototypes