일상의 기록/🌷DAILY 회고록 : 코드스테이츠

[230316] CLASS 상속에서 spuer 참조 시 this를 써버리면..?Error..Error...왱알왱알..

감귤밭호지차 2023. 3. 16. 17:20

🍀 오늘의 날짜 : 23년 03월 16일 
🍀 오늘의 주제 : CLASS 의 상속과 프로토타입

 

🔖 Super 참조

 

 

CLASS 상속할 때, super 키워드를 이용해서, 상위 클래스의 constructor을 호출 할 수 있습니다만, 메소드 내에서 super을 참조하여, 상위 클래스의 메서드를 호출 할 수도 있습니다. 

 

class Rectangle { // 1. 상위 클래스
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }
  getArea() {
    return this.width * this.height;
  }

  toString() {
    return `width = ${this.width}, height = ${this.height}`;
  }
}

class ColorRectangle extends Rectangle { // 2. 하위 클래스
  constructor(width, height, color) {
    super(width, height);   //** super을 이용한 참조
    this.color = color;
  }
  
  //Overriding
  toString() {
    return super.toString() + `, color = ${this.color}`; 
  } 
}
const colorRectangle = new ColorRectangle(2, 4, 'red');

console.log(colorRectangle);  // ColorRectangle {width:2, height:4, color: 'red'}
console.log(colorRectangle.getArea()); // 8
console.log(colorRectangle.toString()); // width = 2, height = 4, color = 'red'

 

위의 예제를 보면 super.toString()을 통해 부모 클래스인 Rectangle의 toString()에 접근 할 수 있었습니다. 그러다 문득 ' this '  를 통해 접근을 시도하면 어떻게 될까 하고 수정을 해보았더니...

 

Error...Error... Maximum call stack size exceeded..

무한하게 함수를 호출해서 stack 이 터져버립니다요... 벗어날 수 없는 무한 개미지옥 

결론은, 메서드 내에서 상위 클래스의 메서드 참조할 때는 나대지말고, " SUPER " 을 사용하자..

 

 

 

# super (상위 클래스 속성)으로 상위 클래스 속성할 때는 한번 만, 메서드를 참조할 때는 여러번 가능합니다. 

 

 

추가 학습 예정
* ES5 문법으로 상속 구현하기
* 인터페이스에 대해 블로깅 하기
* #으로 은닉화 구현해보기
* getter, setter 학습 후 구현하기