(SEB_FE) Section2 Unit2 프로토타입

PYM·2023년 3월 15일
0

(SEB_FE) SECTION2

목록 보기
3/19
post-thumbnail
  • 프로토타입이 무엇인지 설명할 수 있다.
  • 프로토타입과 클래스의 관계에 대해 설명할 수 있다.
  • 프로토타입 체인에 대해 설명할 수 있다.

🏀프로토타입과 클래스

  • 여기서 프로토타입은 원형 객체를 의미한다.

  • JavaScript는 프로토타입(Prototype) 기반 언어
    ➡ 모든 객체들이 메소드와 속성들을 상속 받기 위한 템플릿으로써 프로토타입 객체(prototype object)를 가진다는 의미

  • 정확히 말하면 상속되는 속성과 메소드들은 각 객체가 아니라 객체의 생성자의 prototype이라는 속성에 정의되어 있다.

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

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

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

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

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

// Human의 생성자 함수를는 Human이다. 
Human.prototype.constructor === Human; // true

// Human의 프로토타입은 Human 클래스의 인스턴스인 kimcoding의 `__proto__`이다
Human.prototype === kimcoding.__proto__; // true

// Human 클래스의 sleep 메서드는 프로토타입에 있으며, 
// Human 클래스의 인스턴스 kimcoding에서 kimcoding.sleep으로 사용할 수 있다.
Human.prototype.sleep === kimcoding.sleep; // true 

🏀프로토타입 체인

  • JavaScript에서 상속을 구현할 때에는 프로토타입 체인을 사용

  • extendssuper 키워드를 이용해서 상속을 구현할 수 있다.

🏅 ECMAScript 2015 클래스

  • ECMAScript 2015에서는 C++나 Java와 유사한 클래스 문법을 공개하여 클래스를 조금 더 쉽고 명확하게 재활용 할 수 있게 되었다.

1. Person 클래스 생성

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!`);
  };
}
  • constructor() 메소드는 Person 클래스의 생성자를 의미
  • greeting()farewell()는 멤버 메소드

2. Person 클래스를 상속받는 Teacher 클래스 생성

상속받으려면 extends키워드와 power키워드 사용
상위 클래스(예시의 경우 Person)의 생성자를 호출하며 super()의 매개변수를 통해 상위 클래스의 멤버(예시의 경우 first, last등)를 상속받는 코드⬇️

class Teacher extends Person {
  constructor(first, last, age, gender, interests, subject, grade) {
    // first, last, age, gender, interests는 Person class로부터 상속받음
    super(first, last, age, gender, interests);

    // subject and grade 는 하위 클래스인 Teacher에만 있는 멤버 
    this.subject = subject;
    this.grade = grade;
  }
}

3. Teacher 클래스를 사용해서 snape라는 Object 생성하기
TeacherPerson을 상속받기 때문에
TeacherPerson 양 쪽의 메소드와 속성을 사용할 수 있다. ⬇️

let snape = new Teacher('Severus', 'Snape', 58, 'male', ['Potions'], 'Dark arts', 5);
snape.greeting(); // Hi! I'm Severus.
snape.farewell(); // Severus has left the building. Bye for now.
snape.age // 58
snape.subject; // Dark arts

🏅 DOM과 프로토타입

  • 브라우저에서 DOM을 이용하면, document.createElement('div')로 새로운 div 엘리먼트를 만들 수 있다.
    • 이렇게 생성된 div 엘리먼트는, HTMLDivElement라는 클래스의 인스턴스
  • DOM 엘리먼트는 innerHTML과 같은 속성, 또는 append()와 같은 메서드를 가지고 있다.
  • 각각의 엘리먼트가 모두 해당 메서드나 속성을 가지고 있다.
    즉, Element라는 공통의 부모가 있음을 알 수 있음

이를 통해 우리는 DOM도 상속 관계로 이루어져 있음을 알 수 있다.
__proto__ 를 사용해서 DOM의 상속관계를 확인할 수 있다.

  • div 엘리먼트의 상속 관계
  • EventTarget 의 부모로는, 모든 클래스의 조상인 Object 가 존재
  • 각각의 인스턴스에 __proto__를 이용하면 부모 클래스의 프로토타입, 혹은 '부모의 부모 클래스'의 프로토타입을 탐색할 수 있다. (상속받고 있는 것!)

🏅 DOM의 상속관계를 .__proto__로 알아보는 실습

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__
// {constructor: ... }
div.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__
//null

🏀프로토타입 Quiz 정리

  1. 생성자(constructor) 함수

    • 클래스 내에서 생성자 함수는 하나만 있을 수 있다.

    • 생성자 함수는 인스턴스 객체를 생성하고 초기화하는 특별한 메서드

    • 생성자 함수를 작성하지 않으면, 기본 생성자(default constructor)가 제공됨.
      이때, 기본(base) 클래스일 경우는 기본 생성자는 비어있으며,
      파생(derived) 클래스일 경우 기본 생성자는 부모 생성자를 부름.

  1. super 키워드

    • super 키워드는 부모 클래스의 함수를 호출할 때 사용

    • 생성자 함수 내에서 쓰일때는, super 키워드는 한번만 사용될 수 있다.

    • this 키워드가 사용되기 전에 사용되어야 하며, 안 그러면 Reference 에러

    • 생성자 함수 내에서 super를 호출하면 부모 클래스의 생성자 함수를 호출

  2. 새롭게 생성한 class의 최상위 클래스는 Object 이다.

  3. JavaScript는 프로토타입 기반 언어이며, DOM도 프로토타입으로 상속을 구현

  4. EventTargetprototypeaddEventListener() 메서드가 있다.

    • divHTMLDivElement의 인스턴스이고 EventTarget상속받았기 때문에 addEventListener()를 사용할 수 있는 것.

    • 보통 클래스의 인스턴스는 new 키워드로 생성하지만,
      DOM에서는 createElement()를 사용

profile
목표는 "함께 일하고 싶은, 함께 일해서 좋은" Front-end 개발자

0개의 댓글