JavaScript의 프로토타입 체인(Prototype Chain)은 객체가 다른 객체로부터 속성과 메서드를 상속받는 메커니즘이다. 클래스 기반 언어와 달리, JavaScript는 프로토타입 기반 상속을 사용한다.
프로토타입 기본
javascript
const animal = {
breathe() { return '숨쉬기'; }
};
const dog = Object.create(animal);
dog.bark = function() { return '멍멍'; };
console.log(dog.bark()); // '멍멍' — 자신의 메서드
console.log(dog.breathe()); // '숨쉬기' — 프로토타입에서 상속
// 체인: dog → animal → Object.prototype → null
console.log(Object.getPrototypeOf(dog) === animal); // true
[[Prototype]] 내부 슬롯
javascript
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
return `안녕하세요, ${this.name}입니다`;
};
const alice = new Person('Alice');
console.log(alice.greet()); // '안녕하세요, Alice입니다'
// 체인: alice → Person.prototype → Object.prototype → null
console.log(alice.__proto__ === Person.prototype); // true
console.log(Person.prototype.__proto__ === Object.prototype); // true
속성 탐색 순서
javascript
const base = { x: 1 };
const derived = Object.create(base);
derived.x = 99; // 자신의 x 추가
console.log(derived.x); // 99 (자신의 속성)
console.log(derived.y); // undefined (체인 끝까지 없음)
// hasOwnProperty로 자신의 속성 확인
console.log(derived.hasOwnProperty('x')); // true
console.log(derived.hasOwnProperty('y')); // false
ES6 class와 프로토타입
javascript
class Animal {
constructor(name) { this.name = name; }
speak() { return `${this.name} 소리냄`; }
}
class Dog extends Animal {
speak() { return `${this.name}: 멍멍!`; }
}
const d = new Dog('Rex');
// 실제 체인: d → Dog.prototype → Animal.prototype → Object.prototype → null
// class는 프로토타입 체인의 syntactic sugar
console.log(Object.getPrototypeOf(Dog) === Animal); // true
console.log(Object.getPrototypeOf(Dog.prototype) === Animal.prototype); // true
관련 개념