[OOP] 프로토타입과 클래스, 프로토타입 체인

젬마·2022년 9월 21일
0

codestates

목록 보기
6/18

프로토타입(prototype)이란?

  • 프로토타입(prototype)은 말 그대로 객체의 원형이라고 할 수 있다. 프로토타입에 저장된 속성들은 생성자를 통해서 객체가 만들어질 때 그 객체에 연결된다.

클래스와 인스턴스, 프로토타입의 관계

<레퍼런스>
생활코딩 - JavaScript 객체 지향 프로그래밍 - 15. prototype vs proto)
(https://www.youtube.com/watch?v=wT1Bl5uV27Y)

  • Person 클래스를 정의할 때, 클래스 내부에는 prototype 프로퍼티가 생긴다.

  • Person.prototype은 Person 클래스의 원형 객체를 의미한다. 아래 코드는 Person의 프로토타입 객체에 sum이라는 메소드를 추가하는 것이다.

Person.prototype.sum = function(){}
  • Person의 프로토타입 객체에 있는 constructor(생성자) 함수는 Person 클래스를 가리킨다.

  • Person 클래스를 이용해 kim이라는 인스턴스를 생성한다고 가정하자. 이떄 kim 인스턴스 내부에는 __proto__라는 프로퍼티가 생성되는데, 이는 즉 kim을 생성한 Person 클래스의 원형 객체(프로토타입)을 가리킨다.

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

  • 우리가 흔히 사용하는 배열(arr) 역시 Array 클래스의 인스턴스이기 때문에 클래스와 인스턴스, 프로토타입의 관계를 살펴볼 수 있다.
  • 결국 Arr.prototype.push(...) 등의 내장함수는 Array 클래스의 프로토타입 객체에 내부적으로 저장되어있는 메소드를 뜻한다.
  • arr.__proto__는 배열 arr를 생성한 Array 클래스의 인스턴스, 즉 Array.prototype을 가리킨다.

프로토타입 체인

class Idol {
  constructor(name, age, position) {
    this.name = name;
    this.age = age;
    this.position = position;
  }
  greeting() {
    console.log(
      `안녕하세요! 저는 ${this.position}을 맡고 있는 ${this.name}입니다!`
    );
  }
}
class Entertainment extends Idol {
  constructor(name, age, position, entertainment) {
    super(name, age, position, entertainment);
    this.entertainment = entertainment;
  }
}
class Testar extends Entertainment {
  constructor(name, age, position, entertainment, groupGreeting) {
    super(name, age, position, entertainment);
    this.groupGreeting = "Take your STAR!";
  }
}
let moondae = new Testar('박문대', 26, '메인 보컬', '오르빗');
moondae.greeting(); // 안녕하세요! 저는 메인 보컬을 맡고 있는 박문대입니다!
  • (해당 코드에서) 제일 상위 객체인 Idol 클래스를 생성한 후, extends와 super를 활용하여 Idol의 속성을 상속받는 자식 클래스인 Entertainment와, Entertainment의 속성을 상속받는 자식 클래스인 Testar를 생성한다. 마지막으로 Testar의 인스턴스인 moondae를 생성하였다.
  • moondae.greeting();을 실행시킬 때 값이 반환되는 과정은 다음과 같다.
    • Testar 클래스에는 greeting이 없기 때문에 부모 클래스인 Entertainment로 거슬러 올라간다.
    • 그러나 Entertainment에도 없기 때문에, 한 단계 더 위에 있는 Idol 클래스까지 올라간다. greeting을 찾았으므로 moondae.greeting()의 값을 반환할 수 있게 된다.
  • 이처럼 객체의 어떤 속성에 접근하려할 때 그 객체 자체 속성 뿐만 아니라 객체의 프로토타입, 그 프로토타입의 프로토타입 등 프로토타입 체인의 종단에 이를 때까지 그 속성을 탐색하는 특징을 프로토타입 체인(prototype chain) 이라고 부른다.
profile
취준생은 프론트엔드의 꿈을 꾸는가

0개의 댓글