[JavaScript][TIL] Class를 복사하는 extends / super

Trippy·2023년 11월 20일
0

JavaScript

목록 보기
25/28
post-thumbnail

Class를 상속한 Class를 만들고 싶을 때 쓰는 extends

father class를 하나 만들었다.
father class는 성과 이름이라는 속성을 가지고 있다.

class father {
	constructor(name) {
      this.lastName = "Jeong";
      this.firstName = name;
    }
}

그럼 이제 new father() 이런식으로 하면 새로운 object를 쉽게 생성할 수 있게 된다.

그런데 이 class가 너무 유용한 나머지 이것과 유사한 class를 하나 더 만들고 싶다.

그러면 직접 class를 하나 더 만들어서 내용을 복붙하면 되겠지?

하지만 class안에 복사할 내용이 너무 많으면 코드가 너무 길어진다.


그래서 선대 개발자들이 extends라는 문법을 만들었는데

이걸 이용해서 class를 만들면 기존에 있던 class의 내용을 그대로 복붙해서 만들어낼 수 있다.

있어 보이게 말하면 "다른 class를 상속해서 만들 수 있게 도와주는 문법" 이다.

그래서 할아버지 class를 상속하는 아버지 class를 만들어보자

class Grandfaher{
  constructor(name) {
    this.lastName = "Jeong";
    this.firstName = name;
  }
}

class father extennds grandFather {
}

extends는 이렇게 쓰면 된다.

그럼 이제 grandFather라는 class를 그대로 복붙한 father라는 class가 생성된다

진짜 class가 생겼는지 확인해보고 싶으면 new father(); 이렇게 테스트 해보면 된다..


new father("재용"); 이렇게 하면 성과 이름을 가진 object 자료가 하나 생성된다

grandFather과 똑같은 class가 생겼쥬? extends 끝~~


extends한 class에 새로운 속성을 추가하기

class grandFather {
  constructor(name) {
    this.lastNmae = "Jeong";
    this.firstNmae = name;
  }
}

class father extends grandFather {
  constructor() {
	this.age = 57;
  }
}

이렇게 하면 new father() 했을 떄 생성된 오브젝트들은 {성, 이름, 나이} 속성들을 가지게 된다

하지만 이렇게 했을 때 에러가 난다

super를 써야된다고 에러가 나는 것이다

super

class grandFather {
  constructor(name) {
    this.lastNmae = "Jeong";
    this.firstNmae = name;
  }
}

class father extends grandFather {
  constructor(name) {
    super(name);
	this.age = 57;
  }
}

super()extends로 상속중인 부모 class의 constructor를 의미한다

쉽게 말해서 grandFather class의 constructor()랑 똑같다는 말이다.

class간 함수를 상속 받고 싶을 때

class grandFather {
  constructor(name) {
    this.lastName = "Jeong"; 
    this.firstName = name;
  }
  sayHi(){
    console.log('Hello grandFather')
  }
}

class father extends grandFather {
  constructor(name){
    super(name);
    this.age = 57;
  }
  sayHi2(){
    consoel.log('Hello Father');
    super.sayHi();
  }
}

let a = new father('재용');

a.sayHi2() // 'Hello Father', 'Hello grandFather'

super라는걸 저렇게 prototype 함수 안에서 쓰면 아까의 super와 다른 의미가 된다

여기서의 super는 부모 class의 prototype을 의미한다.

super는 뜻이 두개이다.
1. constructor 안에서 쓰이면 부모 class의 constructor
2. portotype 함수 안에서 쓰이면 부모 class의 prototype

profile
감금 당하고 개발만 하고 싶어요

0개의 댓글