[JavaScript ES6] class와 extends/super로 상속하는 법

dygreen·2022년 7월 11일
0

JavaScript

목록 보기
9/9
post-thumbnail

📝 이전 게시글에서 언급한 constructor를 만드는 ES6 신문법 class에 대해서 다뤄보겠습니다!

📌 class ?

: constructor를 만드는 신문법

// 기존 constructor 만드는 방법
function Parent(){ 
  this.name = 'Kim';
  this.sayHi = function(){
	console.log('hello'); 
  }
}

var child = new Parent();
// ES6 class를 이용해 constructor 만드는 방법
class Parent{
  constructor(){
    this.name = 'Kim';
    this.sayHi = function(){
      console.log('hello');
    }
  }
}

var child = new Parent(); // 상속 방식은 같다.

📌 class에 함수 추가하는 방법

class 부모{
  constructor(){
    this.name = 'Kim';
    this.sayHi = function(){ // 1번 방법
      console.log('hello');
    } 
  }
}
var 자식 = new 부모();
class 부모{
  constructor(){
    this.name = 'Kim';
  }
  sayHi(){ // 2번 방법
    console.log('hello')
  }
}
var 자식 = new 부모();

1번 방법: constructor 안에 추가하기

  • 자식이 직접 함수를 가짐

2번 방법: 아래에 추가하기

  • 자식이 직접 갖지 않고, 부모.prototype에 추가됨

부모.prototype 보는 방법

자식.__proto__; // 1번
Object.getPrototypeOf(자식); // 2번

📌 extends / super

: extends를 통해 부모의 속성을 그대로 상속받을 수 있다.

class 할아버지 {
  constructor(name){
    this.= 'Kim';
    this.이름 = name;
  }
}

class 아버지 extends 할아버지 {
  constructor(name){
    super(name);
    this.나이 = 50;
  }
}

👆 extends만 쓰면 되는 것이 아니라, super()도 함께 써야 된다.
extends해서 만든 class는 this를 그냥 못 쓰고, super() 다음에 써야 함!


여기서 super()

this.= 'Kim';
this.이름 = name;

를 의미한다고 볼 수 있다.


super의 의미

  1. constructor 안에서 쓰면, 부모 class의 constructor를 의미한다.
  2. constructor 밖에서 쓰면, 부모 class의 prototype을 의미한다. (=부모.prototype)

📚 Reference

: 코딩애플 강의

profile
✨감명깊은 앞단을 향한 꾸준한 여정✨

0개의 댓글