자바스크립트 객체는 obj.prop에 접근할 때, 자기 자신에게 없으면
포기하지 않고 숨겨진 [[Prototype]] 링크를 따라 부모 객체로,
그 부모의 부모로 계속 올라가며 찾습니다. 이 사슬을 프로토타입 체인이라 부르고,
체인 끝(null)까지 못 찾으면 undefined가 됩니다.
🔍 속성 조회 시뮬레이터 dog.속성명
namebarkeattoStringfly (없음)
dog (인스턴스, own)
name: "바둑이"legs: 4
↓ [[Prototype]]
Dog.prototype
bark: ƒ()
↓ [[Prototype]]
Animal.prototype
eat: ƒ()legs: 0 (가려짐)
↓ [[Prototype]]
Object.prototype
toString: ƒ()hasOwnProperty: ƒ()
↓ [[Prototype]]
null — 체인의 끝
📋 탐색 로그
// 조회 버튼을 눌러보세요...
🌒 섀도잉(Shadowing) 실험 own property 추가
dog 인스턴스에 bark를 직접 추가하면, 체인을 타고
Dog.prototype까지 올라갈 필요 없이 인스턴스 자신에서 바로 찾습니다.
원본 메서드는 사라진 게 아니라 "가려질(shadow)" 뿐입니다.
🐍 이 체인을 만드는 실제 코드
functionAnimal(name) {
this.name = name;
this.legs = 0;
}
Animal.prototype.eat = function() { return`${this.name}이(가) 먹는다`; };
functionDog(name) {
Animal.call(this, name); // Animal 생성자 재사용this.legs = 4;
}
Dog.prototype = Object.create(Animal.prototype); // 체인 연결
Dog.prototype.bark = function() { return"멍멍!"; };
const dog = newDog("바둑이");
dog.bark(); // "멍멍!" → Dog.prototype 에서 발견
dog.eat(); // "바둑이이(가)..." → 체인을 타고 Animal.prototype 에서 발견
dog.toString(); // 체인을 끝까지 타고 Object.prototype 에서 발견
dog.fly; // undefined → null 까지 못 찾음
dog instanceof Dog; // true → 체인 위에 Dog.prototype이 있는지 검사
dog.hasOwnProperty("name"); // true → 체인을 타지 않고 "자기 자신"만 검사
dog.hasOwnProperty("bark"); // false → bark는 Dog.prototype 소유
class는 이 코드의 문법 설탕(syntactic sugar)입니다.
class Dog extends Animal { ... }도 내부적으로는
똑같이 Dog.prototype의 [[Prototype]]이
Animal.prototype을 가리키도록 연결할 뿐, 탐색 원리는 동일합니다.
또한 obj.__proto__는 [[Prototype]]에 접근하는
(레거시) 방법이고, Dog.prototype은 "Dog로 만들 인스턴스들이 공유할 객체"를
가리키는 전혀 다른 프로퍼티라는 점에 주의하세요.