🧬

프로토타입 체인 — class가 없던 시절의 상속

__proto__, prototype, Object.create()의 관계

const dog = { bark() { return 'woof'; } };
const myDog = Object.create(dog);
myDog.name = 'Max';

myDog.bark();  // 'woof' — myDog에 bark가 없지만 프로토타입 체인으로 찾는다
myDog.name;    // 'Max' — 자기 자신에 있다

proto vs prototype

__proto__ — 모든 객체가 가진 내부 링크. 이 객체의 "부모"를 가리킨다. (정식 이름은 [[Prototype]])

prototype함수만 가진 속성. new Foo()로 생성된 객체의 __proto__Foo.prototype을 가리키게 된다.

function Dog(name) { this.name = name; }
Dog.prototype.bark = function() { return 'woof'; };

const d = new Dog('Max');
d.__proto__ === Dog.prototype  // true
Dog.prototype.__proto__ === Object.prototype  // true
Object.prototype.__proto__ === null  // 체인의 끝

class는 이것의 문법적 설탕

class Dog {
  constructor(name) { this.name = name; }
  bark() { return 'woof'; }
}
// 내부적으로 위의 prototype 기반 코드와 동일하게 동작

class를 쓰든 function을 쓰든 프로토타입 체인은 같다. class가 새로운 상속 모델을 만든 게 아니라, 기존 프로토타입 체인을 읽기 쉽게 포장한 것.

프로퍼티 검색 순서

obj.prop를 접근하면: obj 자체 → obj.proto → obj.proto.proto → ... → null. null에 도달하면 undefined 반환.

hasOwnProperty()로 자기 자신의 프로퍼티인지 프로토타입의 것인지 구분할 수 있다.

핵심 포인트

1

모든 객체는 __proto__(=[[Prototype]])로 부모 객체를 참조

2

new Foo()로 만든 객체의 __proto__는 Foo.prototype을 가리킨다

3

프로퍼티 검색: 자기 자신 → __proto__ → __proto__.__proto__ → null

4

class는 prototype 기반 상속의 문법적 설탕 — 내부 동작 동일

사용 사례

라이브러리 코드 읽기 — prototype 조작을 이해해야 읽을 수 있다 폴리필 구현 — Array.prototype에 메서드를 추가하는 패턴