본문 바로가기
프론트엔드/JavaScript

[ JavaScript ] Class 초기값 설정해주기, 상속 하기

by CODESIGN 2022. 12. 5.

Class 초기값 설정해주기


constructor(생성자)


constructor(생성자)를 이용하면 class 객체의 초기 값을 설정해 줄 수 있다.

단, class 내부에서 constructor는 한 개만 존재할 수 있다.

 

아래는 constructor를 이용하여 Person 클래스에 초기 값을 설정해 보았다.

 

class Person {
  constructor() {
    this.name = 'Sam'; //this 키워드로 프로퍼티 설정해주기
  }

  printName() { // 메서드
    console.log(this.name); // 위의 this.name을 전달 받는다
  }
}

const person = new Person(); // 위의 Person class를 const person에 지정한다.
person.printName(); // 결과: 'Sam'

 

 

Class를 상속하는 방법


아래와 같이 새로운 class Human을 만들어준 뒤 Person에서 extend 한 후 마지막에 person.printGender()을 하면 에러가 난다.

 

class Human { // 새로운 class
  constructor() {
    this.gender = 'male';
  }
  printGender() {
    console.log(this.gender);
  }
}


class Person extends Human { // Human class 추가
  constructor() { // 생성자 함수
    this.name = 'Sam'; //this 키워드로 프로퍼티 설정해주기
  }

  printName() { // 메서드
    console.log(this.name); // 위의 this.name을 전달 받는다
  }
}

const person = new Person(); // 위의 Person class를 const person에 지정한다.
person.printName(); // 결과: 'Sam'
person.printGender();

 

super() 메서드를 추가하라는 에러 메시지가 뜬다. 

 

 

super


상위 클래스의 생성자 함수를 실행한다. 

 

class Human { // 새로운 class
  constructor() {
    this.gender = 'male';
  }
  printGender() {
    console.log(this.gender);
  }
}


class Person extends Human {
  constructor() { 
 	super(); // 추가
    this.name = 'Sam'; 
  }

  printName() { // 메서드
    console.log(this.name);
  }
}

const person = new Person(); 
person.printName();
person.printGender();

// 결과:
// "Sam"
// "male"

 

 

ES6


예전에는 constructor을 사용하였고 그렇기 때문에 this를 활용했어야 했다. 하지만 ES6가 나오면서 constructor을 명시할 필요가 없어졌고 그래서 super()을 사용하지 않아도 된다. 위의 코드를 ES6문법으로 쓴다면 아래와 같이 쓸 수 있다.

 

class Human {
  gender = 'male';

  printGender =() => {
    console.log(this.gender);
  }
}


class Person extends Human {
  name = 'Sam'; //this 키워드로 프로퍼티 설정해주기

  printName = () => { // 메서드
    console.log(this.name); // 위의 this.name을 전달 받는다
  }
}

const person = new Person(); // 위의 Person class를 const person에 지정한다.
person.printName(); 
person.printGender();

// 결과:
// "Sam"
// "male"

 

 

댓글