현대 자바스크립트의 클래스 구조와 상속 구현 방식

클래스 구문정의 기본 구조

ECMAScript 2015(ECMA-6) 에서부터 도입된 클래스 문법은 전통적인 프로토타입 기반 방식을 문법적으로 추상화하여 제공합니다. 이를 통해 객체 지향적 설계 패턴을 보다 명확하게 작성할 수 있으며, 생성자 함수와 멤버 메서드를 하나의 단위로 캡슐화합니다.

class Employee {
  constructor(userId) {
    this.userId = userId;
  }

  showIdentity() {
    console.log(`Identified user: ${this.userId}`);
  }
}

const staff = new Employee('EMP_001');
staff.showIdentity(); // 결과: Identified user: EMP_001

상속 관계 설정 및 super 호출

기존에 정의된 클래스의 기능을 확장하거나 재사용하고자 할 때 상속에 해당하는 `extends` 키워드를 사용합니다. 자식 클래스의 생성자 내에서 부모 클래스의 초기화 로직을 수행하려면 반드시 `super()` 를 명시해야 합니다.

class Trainee extends Employee {
  constructor(userId, department) {
    super(userId); // 부모 생성자 실행
    this.department = department;
  }

  attendTraining() {
    console.log(`${this.userId} attending ${this.department} session.`);
  }
}

const trainee = new Trainee('T_99', 'Backend');
trainee.showIdentity(); // 상속된 메서드 호출
trainee.attendTraining(); // 고유 메서드 호출

스태틱 멤버 활용

인스턴스를 생성하지 않고도 클래스 본체를 통해 접근 가능한 유틸리티 함수나 상수는 `static` 수정자로 선언합니다. 이는 클래스 전체에서 공유되는 컨텍스트를 나타냅니다.

class GeometryUtil {
  static CIRCLE_RATIO = 3.141592;

  static getVolume(radius) {
    return this.CIRCLE_RATIO * radius * radius * radius;
  }
}

// 클래스 직접 호출로 접근
console.log(GeometryUtil.getVolume(3)); 

프로퍼티 접근 제어 (Getter/Setter)

특정 데이터 필드에 대한 읽기 또는 쓰기 작업 시 자동으로 로직이 실행되도록 하려면 액세스러를 정의합니다. 이렇게 하면 내부 상태의 무결성을 유지하면서 외부에서는 마치 일반 속성과 유사하게 동작하도록 만들 수 있습니다.

class DataValidator {
  constructor(baseValue) {
    this._baseValue = baseValue;
  }

  get formattedValue() {
    return `[VALIDATED] ${this._baseValue}`;
  }

  set formattedValue(input) {
    this._baseValue = String(input).trim();
  }
}

const validator = new DataValidator(100);
console.log(validator.formattedValue);
validator.formattedValue = '  200  ';
console.log(validator._baseValue);

프라이빗 필드 보안 강화

최신 표준 (ES2022 등) 에서는 클래스 외부에서의 접근을 완전히 차단하기 위해 이름 앞에 해시 기호 (#) 를 붙이는 방식으로 실제 프라이빗 필드를 구현할 수 있습니다. 해당 식별자는 인스턴스 외부에서 참조 시 오류가 발생합니다.

class SecureStorage {
  #secretKey = null;

  initialize(key) {
    this.#secretKey = key;
  }

  isAuthorized() {
    return this.#secretKey !== null;
  }
}

const storage = new SecureStorage();
storage.initialize('xyz-token');
console.log(storage.isAuthorized()); // true
// console.log(storage.#secretKey); // ReferenceError 발생 예상

타입 체크 및 원형 확인

생성된 인스턴스가 특정 클래스에서 유래했는지 판별하는 과정에는 `instanceof` 연산자를 주로 사용합니다. 또한 객체의 프로토타입 체인을 직접 확인하여 원형 객체가 일치하는지 검증할 수도 있습니다.

console.log(trainee instanceof Trainee);      // true
console.log(trainee instanceof Employee);     // true (부모까지 포함됨)
console.log(Object.getPrototypeOf(trainee) === Trainee.prototype); // true

태그: JavaScript ES6 Class Inheritance OOP

6월 27일 18:41에 게시됨