prototypeinheritance
prototype chain을 설명해 주세요
- 예상 시간
- 7분
30초 답변
꼬리질문
조금 더 깊게 물어본다면
답변 뒤에 이어질 수 있는 질문들을 하나씩 열어볼 수 있어요.
`__proto__`와 `prototype`은 같은 건가요?
property lookup은 어떤 순서로 일어나나요?
class 문법은 prototype과 무관한가요?
prototype chain을 직접 깊게 만들면 어떤 문제가 있나요?
부가 설명
const parent = {
sayHello() {
return "hello";
},
};
const child = Object.create(parent);
child.name = "Joon";
child.name; // "Joon"
child.sayHello(); // "hello"child 자신에게는 sayHello가 없습니다. 그래도 호출할 수 있는 이유는 child의 prototype인 parent에서 method를 찾기 때문입니다.
class도 비슷하게 볼 수 있습니다.
class User {
greet() {
return "hi";
}
}
const user = new User();
user.greet();greet는 보통 각 instance에 복사되는 것이 아니라 User.prototype에 있고, instance가 prototype chain을 통해 찾아갑니다.
prototype chain은 재사용을 가능하게 하지만, 너무 깊거나 예측하기 어려운 chain은 디버깅을 어렵게 만들 수 있습니다. 직접 prototype을 만지는 경우보다 class, object literal, library 내부 구현에서 간접적으로 접하는 경우가 많습니다.
__proto__, prototype, constructor는 서로 다른 층위의 개념입니다. prototype은 함수 객체가 instance에게 연결해 줄 객체이고, instance의 내부 prototype 링크는 그 객체를 가리킵니다.
한 줄 정리
prototype chain은 객체에 없는 property를 연결된 prototype을 따라 올라가며 찾는 JavaScript의 상속 구조입니다.