[JS] 프로토타입(Prototype)

TATA·2023년 1월 13일
0

JavaScript

목록 보기
16/25

✔️ 프로토타입(Prototype)이란?

JavaScript는 프로토타입 기반 언어이다.
여기서 프로토타입(Prototype)은 원형 객체를 의미한다.
(객체의 원형, 즉 객체의 부모가 가지는 유전자 = 상속받는 데이터, 메소드)

prototype : 내가 원형일 때 존재함.
                        함수 객체만 가지고 있음.
                        생성자를 가지는 원형으로 선언 가능.

__proto__ : 나의 원형을 가리킴.
                        모든 객체가 가지고 있음.
                        하나의 링크라고 할 수 있음.

상속은 .prototype을 통해서 가능하다면,
인스턴스 자신의 프로퍼타입 확인은 .__proto__를 통해서 가능하다.

OOP 패턴으로 구현한 Human 예시👇

class Human {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  sleep() {
    console.log(`${this.name}은 잠에 들었습니다`);
  }
}

let kimcoding = new Human('김코딩', 30);

Human.prototype.constructor === Human; // true
Human.prototype === kimcoding.__proto__; // true
Human.prototype.sleep === kimcoding.sleep; // true

Human이라는 클래스와 인스턴스, 그리고 프로토타입의 관계

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

우리가 흔히 쓰는 배열 역시 원리가 동일하다.
배열은 Array 클래스의 인스턴스이며, 프로토타입에는 다양한 메서드가 존재한다.

Array.prototype.constructor === Array; // true
Array.prototype === [1,2,3].__proto__; // true
Array.prototype.name === [1,2,3].name; // true

👉 프로토타입 체인 보러가기

profile
🐾

0개의 댓글