(TIL) D+21 객체 지향 프로그래밍, 프로토타입 체인

JulyK9·2022년 7월 25일
0

프로토타입 체인

  • 객체지향 프로그래밍(OOP)특성 중 ‘상속’을 구현할 때 사용
  • 부모 클래스 : 속성과 메서드를 물려주는 클래스
  • 자식 클래스 : 속성과 메서드를 물려받는 클래스
  • 상속의 과정 구현 : extends 와 super 키워드를 이용
    • extends 키워드로 상속받을 클래스를 명시해줌
    • 생성자 함수 내에서 super 키워드를 이용해 상위 클래스의 생성자를 호출하여 상위 클래스의 멤버를 상속받을 수 있음
  • 예제코드
class Person {
  constructor(first, last, age, gender, interests) {
    this.name = {
      first,
      last
    };
    this.age = age;
    this.gender = gender;
    this.interests = interests;
  }

  greeting() {
    console.log(`Hi! I'm ${this.name.first}`);
  };

  farewell() {
    console.log(`${this.name.first} has left the building. Bye for now!`);
  };
}
// Person을 class 문법으로 상속받아 Teacher 클래스 만들기 => 하위 클래스를 생성
// 생성자함수 안에서 첫번째로 super 키워드를 사용해서 상위 클래스 생성자를 호출하여 매개변수를 통해 상위 클래스 멤버를 상속받을 수 있음 

class Teacher extends Person {
  constructor(first, last, age, gender, interests, subject, grade) {
    super(first, last, age, gender, interests);

    // subject and grade are specific to Teacher
    this.subject = subject;
    this.grade = grade;
  }
}
  • 부모 클래스의 프로토타입, 부모의 부모클래스의 프로토타입을 확인하는 방법 ⇒ 접근자 프로퍼티 proto**** 활용

DOM과 프로토타입

  • document.createElement('div')로 생성된 div엘리먼트는, HTMLDivElement라는 클래스의 인스턴스임
  • div 엘리먼트의 상속 관계 확인(아래)


// 인스턴스의 접근자 프로퍼티인 __proto__를 이용해서 부모 클래스의 프로토타입, 부모의 부모 클래스의 프로토 타입을 탐색할 수 있음

let div = document.createElement('div');

div.__proto__ 
div.__proto__.__proto__
div.__proto__.__proto__.__proto__
div.__proto__.__proto__.__proto__.__proto__
div.__proto__.__proto__.__proto__.__proto__.__proto__
div.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__
div.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__

  • 다형성의 핵심 단어 오버로딩

    • 클래스에서 부모 클래스에서 정의한 메서드를 자식클래스에서 재정의해서 사용할 경우
  • .prototype 은 클래스에서 프로토타입에 접근할 때

  • __proto__ 는 인스턴스에서 프로토타입에 접근할 때

  • 왜 메서드일까? 객체 안에 있는 함수
    → 프로토타입 === 원형객체 ⇒ 원형객체 안에 있으므로 메서드라고 함

profile
느리지만 꾸준하게. 부족하거나 잘못된 부분은 알려주시면 감사하겠습니다.

0개의 댓글