프로토타입(Prototype)이란?
- Java의 클래스 기반 객체지향 프로그래밍 언어와 달리 JavaScript는 프로토타입 기반 객체지향 프로그래밍 언어이다.
- JavaScript에서 기본 데이터 타입을 제외한 모든 것은 객체이며 모든 객체는 자신의 부모 역할을 담당하는 객체와 연결되어 있다. 또한 부모 객체로부터 프로퍼티와 메서드를 상속받는데 이러한 정보를 제공하는 객체(부모 객체)를 프로토타입이라 한다.
class Human {
constructor(name, age) {
this.name = name;
this.age = age;
}
sleep() {
console.log(`${this.name}는(은) 잠에 들었습니다`);
}
}
let steve = new Human('스티브', 30);
Human.prototype.constructor === Human; // true
Human.prototype === cat.__proto__; // true
Human.prototype.sleep === cat.sleep; // true
Human 클래스와 인스턴스, 프로토타입의 관계

Array(배열) 클래스와 인스턴스, 프로토타입의 관계

- 우리가 흔히 쓰는 배열도 동일한 원리이다. 배열은 Array 클래스의 인스턴스이며 Array.prototype에는 다양한 메서드가 존재한다.
프로토타입 체인
- JavaScript에서 객체 지향 프로그래밍의 특성 중 상속을 구현할 때에는 프로토타입 체인을 사용한다.
// Human 클래스의 속성과 메서드 예시
let steve = new Human('스티브', 30);
// 속성
steve.age;
steve.gender;
// 메서드
steve.sleep();
steve.eat();
- 학생은 학생이기 이전에 사람이기 때문에 Student 클래스는 Human의 기본적인 메서드를 상속받을 수 있다. 다만, 학생은 일반적인 사람의 특징에 추가적인 특징이 필요하다.
// Student 클래스의 속성과 메서드 예시
let james = new Student('제임스', 15);
// 속성
james.grade;
// 메서드
james.learn();
- Student는 Human의 특징을 그대로 물려받는다. 이렇게 속성과 메서드를 물려주는 클래스를 부모 클래스, 속성과 메서드를 물려받는 클래스를 자식 클래스라고 하며 이 과정을 상속이라고 한다.
DOM과 프로토타입
let div = document.createElement('div');
div.__proto__ // HTMLDivElement
div.__proto__.__proto__ // HTMLElement
div.__proto__.__proto__.__proto__ // Element
div.__proto__.__proto__.__proto__.__proto__ // Node
div.__proto__.__proto__.__proto__.__proto__.__proto__ // EventTarget
div.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__ // { ... }
div.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__ // null
- DOM을 이용해서 새로운 div 엘리먼트를 만들고 __proto__를 통해 확인해보면 div는 HTMLDivElement라는 클래스의 인스턴스라는 것을 알 수 있다.
- 모든 객체들이 메소드와 속성들을 상속 받기 위한 템플릿으로써 프로토타입 객체를 가지며 프로토타입 객체는 또 다시 상위 프로토타입 객체로부터 메소드와 속성을 상속 받을 수도 있고 그 상위 프로토타입 객체도 마찬가지로 상속 받을 수 있다. 이를 프로토타입 체인(prototype chain)이라고 한다.