Chapter2. 프로토타입
2-1. 프로토타입과 클래스
프로토타입
prototype
- 자바스크립트의 모든 객체는 자신의 부모 역할을 담당하는 객체(a.k.a Prototype 또는 Prototype 객체)와 연결되어 있음
- 이러한 연결을 통해 부모 객체의 프로퍼티 또는 메소드를 상속받아 사용할 수 있음
- 자바스크립트의 모든 객체는 내장 프로퍼티인 프로토타입을 가짐
__proto__
속성으로 접근 가능함
.__proto__
- 특정 객체의 프로토타입 객체(a.k.a prototype)에 접근할 수 있는 프로포티(property)
__proto__
속성에 접근하면 내부적으로 Object.getPrototypeOf
가 호출되어 프로토타입 객체(a.k.a prototype)를 반환
클래스, 인스턴스, 프로토타입의 관계
- 프로토타입 객체(a.k.a Prototype)는 생성자 함수에 의해 생성된 각각의 객체(인스턴스)에 공유 프로퍼티를 제공
- 프로토타입 객체(a.k.a Prototype)는 모든 인스턴스에서 공유하기 때문에 정의하는 즉시 별도의 갱신 과정 없이 접근이 가능
class Human {
constructor(name, age) {
this.name = name;
this.age = age;
}
eat() {
console.log(`${this.name}은 밥을 먹습니다.`);
}
}
let andrew = new Human('Andrew', 25);
Human.prototype.constructor === Human;
Human.prototype === andrew.__proto__;
Human.prototype.eat === andrew.eat;