프로토타입 체인 상속

jina Seo·2022년 11월 21일
0

프로토타입 체인 상속

class Grub {
  // TODO..
  constructor(age, color,food){
    this.age = 0;
    this.color = 'pink' 
    this.food = 'jelly'
  }
  eat(){
    return 'Mmmmmmmmm '+ this.food
  }
}
const Grub = require('./Grub');
class Bee extends Grub {
  // TODO..
  constructor(age, color, food, job){
    super(food)
    this.age = 5
    this.color = 'yellow'
    this.job = `Keep on growing`
  }
}
  • extends와 부모 클래스를 상속받음, super키워드는 부모 클래스의 생성자 함수를 호출할때 사용함

    -> 메서드는 오버라이딩되어 bee에서도 eat메서드를 사용가능함

    -> (https://velog.io/@bigbrothershin/JavaScript-class-%EC%98%A4%EB%B2%84%EB%9D%BC%EC%9D%B4%EB%94%A9)
  • 생성자 함수는 인스턴스 객체를 생성하고 초기화하는 특별한 메서드
  • 생성자 함수를 작성하지 않으면 기본 생성자가 제공됨, 기본 클래스일 경우 기본 생성자는 비어있고 파생 클래스일 경우 기본 생성자는 부모 생성자를 부름
  • super키워드는 this키워드를 사용하기전에 사용해야함, 아니면 레퍼런스 에러가 나게됨
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

image

DOM과 프로토타입

  • 브라우저에서 DOM을 이용하면, document.createElement('div')로 새로운 div 엘리먼트를 만들 수 있습니다. 이렇게 생성된 div 엘리먼트는, HTMLDivElement라는 클래스의 인스턴스입니다.

  • DOM 엘리먼트는 예를 들어 innerHTML과 같은 속성, 또는 append()와 같은 메서드가 있습니다. 각각의 엘리먼트가 해당 메서드나 속성이 있다는 것을 통해, Element라는 공통의 부모가 있음을 알 수 있습니다.
    image

  • 화살표 방향은 부모를 가리킵니다. EventTarget의 부모로는, 모든 클래스의 조상인 Object가 존재합니다.

profile
운동하는 개발자가 꿈입니다?

0개의 댓글