Vanilla JS

자바스크립트 클래스2

감말랭이 2023. 4. 20. 22:09

클래스 필드 Class Field

클래스 블록 안에서 할당 연산자를 이용해 인스턴스 속성을 지정할 수 있는 문법

예시

class Counter {
  static initial = 0; // static class field
  count = Counter.initial; // class field
  inc() {
    return this.count++;
  }
}

const counter = new Counter();
console.log(counter.inc()); // 0
console.log(counter.inc()); // 1

Counter.initial = 10;
console.log(new Counter().count); // 10

 

클래스 필드와 this

class 블록은 새로운 블록 스코프를 형성하고, 내부에서 사용된 this는 인스턴스 객체를 가리킴

class MyClass {
  a = 1;
  b = this.a;
}

new MyClass().b; // 1

화살표 함수를 통해서 메소드를 정의할 수 있음

class MyClass {
  a = 1;
  getA = () => {
    return this.a;
  }
}

new MyClass().getA(); // 1

클래스 상속

클래스 상속(class inheritance, subclassing) 기능을 통해 한 클래스의 기능을 다른 클래스에서 재사용 가능

예시

class Parent {
  // ...
}

class Child extends Parent {
  // ...
}

이 관계를 보고 '부모 클래스-자식 클래스 관계' 혹은 '슈퍼 클래스(superclass)-서브 클래스(subclass) 관계'라고 말하기도 함

 

어떤 클래스 A가 다른 클래스 B를 상속받으면, 다음과 같은 일들이 가능해짐

- 자식 클래스 A를 통해 부모 클래스 B의 정적 메소드와 정적 속성을 사용할 수 있음

- 부모 클래스 B의 인스턴스 메소드와 인스턴스 속성을 자식 클래스 A의 인스턴스에서 사용할 수 있음

예시

class Parent {
  static staticProp = 'staticProp';
  static staticMethod() {
    return 'I\'m a static method.';
  }
  instanceProp = 'instanceProp';
  instanceMethod() {
    return 'I\'m a instance method.';
  }
}

class Child extends Parent {}

console.log(Child.staticProp); // staticProp
console.log(Child.staticMethod()); // I'm a static method.

const c = new Child();
console.log(c.instanceProp); // instanceProp
console.log(c.instanceMethod()); // I'm a instance method.

 

super

자식 클래스에서 부모 클래스의 정적 속성과 인스턴스 속성에 접근할 수 있음 하지만, 자식 클래스에 같은 이름의 속성을 정의한 경우 문제가 생김

예시

class Melon {
  getColor() {
    return '제 색깔은 초록색입니다.';
  }
}

class WaterMelon extends Melon {
  getColor() {
    return '속은 빨강색입니다.';
  }
}

const waterMelon = new WaterMelon();
waterMelon.getColor(); // 속은 빨강색입니다.

이런 경우에, super 키워드를 통해 부모 클래스의 메소드에 직접 접근 가능

예시

class Melon {
  getColor() {
    return '제 색깔은 초록색입니다.';
  }
}

class WaterMelon extends Melon {
  getColor() {
    return super.getColor() + ' 하지만 속은 빨강색입니다.';
  }
}

const waterMelon = new WaterMelon();
waterMelon.getColor(); // 제 색깔은 초록색입니다. 하지만 속은 빨강색입니다.

super의 동작 방식

- 생성자 내부에서 super를 함수처럼 호출하면, 부모 클래스의 생성자가 호출됨

- 정적 메소드 내부에서는 super.prop과 같이 써서 부모 클래스의 prop 정적 속성에 접근할 수 있음

- 인스턴스 메소드 내부에서는 super.prop과 같이 써서 부모 클래스의 prop 인스턴스 속성에 접근할 수 있음

예시

class Person {
  constructor({name, age}) {
    this.name = name;
    this.age = age;
  }
  introduce() {
    return `제 이름은 ${this.name}입니다.`
  }
}

class Student extends Person {
  constructor({grade, ...rest}) {
    // 부모 클래스의 생성자를 호출할 수 있음
    super(rest);
    this.grade = grade;
  }
  introduce() {
    // 부모 클래스의 `introduce` 메소드를 호출할 수 있음
    return super.introduce() + ` 저는 ${this.grade}학년입니다.`;
  }
}

const s = new Student({grade: 3, name: '홍길동', age: 19});
s.introduce(); // 제 이름은 홍길동입니다. 저는 3학년입니다.