프로토타입 이해하기

최정석·2022년 5월 26일
0

프로토타입 체인

  • 객체 지향 프로그래밍의 특성 중 상속을 JavaScript에서 구현할 때에는 프로토타입 체인을 사용한다.
  • 속성과 메서드를 물려주는 클래스를 부모 클래스, 속성과 메서드를 물려받는 클래스를 자식 클래스 그리고 이 과정을 상속 이라고 한다.
  • 자바스크립트에서는 extendssuper 키워드를 이용해 상속을 구현할 수 있다.
    class Teacher extends Person {
      constructor(first, last, age, gender, interests, subject, grade) {
        this.name = {
          first,
          last
        };
    
      this.age = age;
      this.gender = gender;
      this.interests = interests;
      // subject and grade are specific to Teacher
      this.subject = subject;
      this.grade = grade;
      }
    } //extends 키워드만 이용해서 상속을 표현 했을때
    
    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;
      }
    } // super 키워드까지 이용해서 상속을 표현 했을때
    
    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
  • 부모 클래스를 수정하지 않고 자식 클래스를 생성한 것처럼 또 다른 자식 클래스를 생성할 수 있다.

MDN에서 메서드를 검색 했을 때 .prototype이 자주 등장하던 이유

이번 이틀간 학습기간 전 수많은?!(내 기준) 메서드를 검색 했을 때 많은 키워드에서 prototype이 자주 보여서 사용할 때 .prototype을 같이 써야하나 라는 고민을 했던 것 같다. 굳이 붙이지 않아도 메서드는 잘 실행됐다. 그래서 난 더 의문이 생겼다. 왜 써있을까?

과제를 진행하던 나는 나도 모르게 class를 생성했고
그 class의 부모인 Object에 내장 되어 있는 인스턴스 메서드를 상속받아서 사용 했던 것이었다.
이번 학습기간을 통해 완전히 분명해진 것은 아니지만 그래도 조금은 뚜렷해졌다.


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__

이 과정을 콘솔에 입력하면 더 명확해진다.
마지막 출력 값이 Object.prototype이 나오기 때문이다.

🔑 나는 그래서 이 프로토타입은
우리가 각 자식 클래스마다 메서드를 따로 쓰는 번거로움을 덜어주는 녀석이라고 이해했다.

profile
코딩, 널 가지러 왔다!

0개의 댓글