JS중급_extends

Adrian·2022년 3월 15일
0
post-thumbnail

▶️ class를 상속할때 쓰는 extends

  class grandfather {
      constructor(name, name2) {
          this.= "Kim";
          this.이름 = name;
          this.이름2 = name2;
      }

      sayHello() {
          console.log("안녕");
      }

      sayHi() {
          console.log("안녕 저는 할아버지에요");
      }
  }

  class father extends grandfather {
      constructor(name, name2) {
          super(name, name2);  //필수로 가져와야
          this.age = 50;
      }

      sayHi() {
          console.log("안녕 저는 아버지에요"); // 메서드 오버라이딩
          super.sayHi(); //부모 prototype에 있는 sayHi 함수를 실행시켜라. 
      }
  }

  let myGranpa = new grandfather('최고','민수');

  console.log(myGranpa); //¡{성: 'Kim', 이름: '최고', 이름2: '민수'}

  myGranpa.sayHi();// 안녕 저는 할아버지에요


//
  • class안에 복사할 내용이 너무 많아지면 코드가 너무 길어지는데, 이를 방지하기 위해 활용할 수 있는 것이 extends 문법이다.
  • super()는 'extends로 상속 중인 부모 class 의 constructor' 를 의미한다.
  • this를 쓰기 전에 super()를 사용하지 않으면 에러를 출력한다. 즉 this를 쓰기 전에 super를 먼저 사용해야한다.
  • new 함수에 파라미터를 넣지 않으면 인수를 넘겨받는 변수의 key값은 underfined로 출력된다.

▶️ 메서드를 실행시키는 과정

  1. f1 object에 메서드가 있는지 보고
  2. 없으면 father.prototype에 메서드가 있는지 보고
  3. 없으면 grandfather.prototype에 메서드가 있는지 본다.
  • 이런 식으로 sayHello를 실행하기 위해 부모를 조사한다.

profile
관조, 사유, 끈기

0개의 댓글