[JS] class

Im-possible·2025년 4월 24일

class

- class는 함수이며, 선언문과 표현식 방식으로 사용
- 생성자 함수를 쉽게 기술해주고, 객체를 생성하고 prototype 기반의 상속을 보다 명료하게 표현
- class 선언문은 호이스팅이 되지만, TDZ 제한으로 인해 초기화 전에 호출하면 에러 발생

class 선언문

class ClassName {
  ...
}

class 표현식

const ClassName = class {
  ...
}

class 메서드 정의

- 멤버 변수의 초기화는 constructor 메서드에 정의
- class의 바디에는 클래스 멤버변수(속성)와 메서드 정의

constructor 메서드

- 객체를 생성하고 초기화하는 메서드(생략 가능)
- 하나만 작성 가능
- super()로 부모의 생성자 호출 가능
class HighSchool{
  constructor(kor, eng){
    this.kor = kor;
    this.eng = eng;
  }
}

const s1 = new HighSchool(100, 91);

prototype 메서드 정의

- 클래스 내부에 생성
- 클래서 인스턴스 생성 후 인스턴스.메서드명()으로 호출
class HighSchool{
  constructor(kor, eng){
    this.kor = kor;
    this.eng = eng;
  }
  
  // prototype 메서드 정의
  sum() {
    return this.kor + this.eng;
  }
  avg() {
    return Math.round(this.sum() / 2);
  }
}

const s1 = new HighSchool(100, 91);
console.log(s1.sum());
console.log(s1.avg());

class 상속

extends

- 상속을 통해 자식 클래스 정의
- class 자식클래스명 extends 부모클래스명 {}
class HighSchool{
  constructor(kor, eng){
    this.kor = kor;
    this.eng = eng;
  }
  sum() {
    return this.kor + this.eng;
  }
  avg() {
    return Math.round(this.sum() / 2);
  }
}

const s1 = new HighSchool(100, 91);
console.log(s1.sum());
console.log(s1.avg());


class College extends HighSchool{
  constructor(kor, eng){
    super(kor, eng); // 부모(HighSchool)의 생성자 호출
  }
	
  // 자식 함수에서 메서드 추가 가능
  grade(){
    let level = 'F';
    const avg = this.avg();
    if(avg >= 90){
      level = 'A';
    }else if(avg >= 80){
      level = 'B';
    }else if(avg >= 70){
      level = 'C';
    }else if(avg >= 60){
      level = 'D';
    }
    return level;
  }
}

const c1 = new College(80, 99);
console.log(c1.sum());
console.log(c1.avg());
console.log(c1.grade());
  • 자식 함수에서 constructor를 생략할 경우 자동으로 constructor가 생성되며 부모의 생성자 함수를 가져오게 된다.
  • constructor를 생성하고 super()를 생략할 경우 에러가 발생한다.
// constructior()를 생략할 경우 자동으로 추가
  constructor(...args){
    super(...args);
  }

0개의 댓글