티스토리 뷰

 

심화 자료구조(양방향, 단방향 연결 리스트, 이진 트리등)를  학습할 예정인데, 학습하려는 모든 자료구조에 대한 새로운 클래스를 정의하기 위해 ES2022 JavaScript의 클래스 문법에 대해  한 번 정리해 보려고 한다.

 

ES2022 클래스 구문 개요

 단방향 연결리스트, 양방향 연결리스트, 스택, 큐 등 다양한 자료 구조를 구현할 것이다. JavaScript는 이 중 어떤 자료 구조도 사전에 포함시켜서 제공하지 않는다.

따라서 익숙해져야 할 것들은 다음과 같다:

  • 클래스 핵심 용어
  • 생성자(constructor) 작성
  • new 연산자를 통한 인스턴스화

클래스란 무엇인가?

일반적으로, 사전에 정의된 속성 및 메서드를 이용해 객체를 생성하기 위한 청사진이다. 패턴을 만들면 객체들을 인스턴스화할 수 있다.

 

인스턴스화(Instantiation)란?

  • 클래스: 청사진 - 설계도
  • 인스턴스: 설계도대로 만들어진 자동차
  • 인스턴스화: 설계도대로 자동차를 찍어내는 일.

 

JavaScript와 클래스의 진실

JavaScript는 실제로는 전통적인 의미의 클래스를 지원하지 않는다. MDN에 따르면, JavaScript 클래스들은 주로 JavaScript에 이미 존재하는 프로토타입 기반 상속에 대한 syntactic sugar(문법적 설탕)이다.

그럼에도 클래스를 정의하고 개별 인스턴스를 생성할 수 있는, JavaScript에서의 패턴을 정의할 것이다. 자료구조를 이해하기 위한 형식으로 클래스를 채택한 것이다. 따라서 진실은, 잠시 알아만 두자.

클래스 키워드

ES2022에서는 class 키워드로 클래스를 선언한다. ES2022부터는 퍼블릭 클래스 필드를 constructor 외부에서 직접 선언할 수 있다.

// 클래스 선언
class Student {
  // 퍼블릭 필드 선언 (ES2022)
  firstName;
  lastName;
  grade;

  // 생성자
  constructor(firstName, lastName, grade) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.grade = grade;
  }
}

// new로 객체 생성
const firstStudent = new Student("Colt", "Steele", 3);
const secondStudent = new Student("Jane", "Doe", 4);

console.log(firstStudent); 
// Student { firstName: 'Colt', lastName: 'Steele', grade: 3 }

제공된 데이터는 생성자로 전달되고, 클래스 인스턴스가 생성될 때 이 생성자가 실행된다.


인스턴스 메서드

인스턴스 메서드는 특정 인스턴스에 내장되어 있다기보다, 특정한 단일 인스턴스에 적용되는 기능을 제공한다. this는 개별 인스턴스를 참조한다.

class Student {
  // 퍼블릭 필드 (ES2022)
  firstName;
  lastName;
  grade;
  tardies = 0;
  scores = [];

  constructor(firstName, lastName, grade) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.grade = grade;
  }

  // 인스턴스 메서드
  fullName() {
    return `${this.firstName} ${this.lastName}`;
  }

  markLate() {
    this.tardies += 1;
    if (this.tardies >= 3) {
      return "You are expelled!";
    }
    return `${this.firstName} ${this.lastName} has been late ${this.tardies} times`;
  }

  addScore(score) {
    this.scores.push(score);
    return this.scores;
  }

  calculateAverage() {
    let sum = this.scores.reduce((a, b) => a + b, 0);
    return sum / this.scores.length;
  }
}

const student1 = new Student("John", "Doe", 2);
console.log(student1.fullName()); // "John Doe"
student1.markLate(); // "John Doe has been late 1 times"
student1.addScore(85);
student1.addScore(92);
console.log(student1.calculateAverage()); // 88.5

클래스 메서드 추가하기

클래스 메서드(정적 메서드)는 메서드 정의 앞부분에 static 키워드를 추가하여 정의한다. 이 키워드는 클래스 자체에 종속되는 반면, 클래스의 개별 인스턴스에는 종속적이지 않다.

MDN에 따르면, static 키워드는 클래스의 정적 메서드나 정적 속성을 정의한다. 정적 메서드는 클래스의 인스턴스화 없이도 호출될 수 있으며, 클래스 인스턴스를 통해서는 호출될 수 없다.

class Student {
  firstName;
  lastName;
  grade;

  constructor(firstName, lastName, grade) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.grade = grade;
  }

  fullName() {
    return `${this.firstName} ${this.lastName}`;
  }

  // 클래스 메서드 (static)
  static enrollStudents(...students) {
    // 여러 학생을 등록하는 유틸리티 함수
    return students.length > 1 
      ? "Enrolling multiple students" 
      : "Enrolling a student";
  }

  static compareGrades(student1, student2) {
    return student1.grade - student2.grade;
  }
}

// 클래스 메서드는 클래스 이름으로 직접 호출
console.log(Student.enrollStudents()); // "Enrolling a student"

const alex = new Student("Alex", "Kim", 3);
const bella = new Student("Bella", "Park", 4);

console.log(Student.compareGrades(alex, bella)); // -1

// 인스턴스에서는 호출 불가
// alex.enrollStudents(); // TypeError: alex.enrollStudents is not a function

MDN의 Point 코드 예제

class Point {
  x;
  y;

  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  // 정적 메서드
  static distance(a, b) {
    const dx = a.x - b.x;
    const dy = a.y - b.y;
    return Math.hypot(dx, dy);
  }
}

const p1 = new Point(5, 5);
const p2 = new Point(10, 10);

console.log(Point.distance(p1, p2)); // 7.0710678118654755

이들은 애플리케이션을 위한 유틸리티 기능을 생성하기 위해 자주 사용된다.

 

마무리

  • 클래스: 인스턴스로 알려진 객체를 생성하기 위한 청사진이다.
  • 이런 클래스들은 new 키워드를 통해 생성되거나 인스턴스화된다.
  • 생성자 함수: 클래스가 인스턴스화될 때 실행되는 특별한 함수다.
  • new를 통해 Student 클래스를 인스턴스화하면 → Student의 constructor가 먼저 실행된다.
  • 인스턴스 메서드: 메서드/객체와 유사한 방식으로 클래스에 추가된다.
  • 클래스 메서드: static 키워드와 함께 추가된다.
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/10   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함