자바스크립트 클래스

찌끅·2024년 7월 29일

클래스

자바스크립트에서 클래스(Class)는 객체 지향 프로그래밍(OOP) 패러다임을 지원하는 문법적 설탕으로, 생성자 함수와 프로토타입 기반 상속을 보다 직관적이고 명확하게 작성할 수 있도록 해준다. 자바스크립트의 클래스는 ES6에서 도입되었다.

클래스 선언

클래슨느 class 키워드를 사용하여 선언한다. 클래스 선언은 아래와 같은 기본 형태를 가진다.

class MyClass {
  // 클래스의 생성자 메서드
  constructor(name) {
    this.name = name; // 인스턴스 변수 초기화
  }

  // 클래스 메서드
  sayHello() {
    console.log(`Hello, ${this.name}!`);
  }
}

클래스 인스턴스 생성

클래스는 new 키워드를 사용하여 인스턴스를 생성한다.

const myInstance = new MyClass('Alice');
myInstance.sayHello(); // "Hello, Alice!"

클래스의 구성 요소

  1. 생성자(constructor)
    • constructor 메서드는 클래스의 인스턴스를 초기화하는 특수한 메서드이다. 클래스가 인스턴스화될 때 자동으로 호출된다.
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}
  1. 메서드(method)
    • 클래스 내부에 정의된 함수이다. 메서드는 인스턴스 메서드와 정적 메서드로 나뉜다.
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  // 인스턴스 메서드
  greet() {
    console.log(`Hello, my name is ${this.name}.`);
  }

  // 정적 메서드
  static describe() {
    console.log('Persons are awesome!');
  }
}

인스턴스 메서드는 클래스 인스턴스에서 호출할 수 있으며, 정적 메서드는 클래스 자체에서 호출할 수 있습니다.

const person1 = new Person('Bob', 25);
person1.greet(); // "Hello, my name is Bob."

Person.describe(); // "Persons are awesome!"
  1. 상속(inheritance)
    • extends 키워드를 사용하여 클래스를 상속할 수 있다. 하위 클래스는 부모 클래스의 속성과 메서드를 상속 받는다.
class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name); // 부모 클래스의 생성자 호출
    this.breed = breed;
  }

  speak() {
    console.log(`${this.name} barks.`);
  }
}

const dog = new Dog('Rex', 'German Shepherd');
dog.speak(); // "Rex barks."

위 예제에서 Dog 클래스는 Animal 클래스를 상속받는다. Dog 클래스는 Animal 클래스의 name 속성과 speak 메서드를 상속받지만, speak 메서드를 재정의(overriding)하여 자신만의 speak 메서드를 구현한다.

super키워드

super 키워든느 부모 클래스의 생성자 또는 메서드를 호출하는 데 사용된다.

부모 클래스의 생성자 호출

자식 클래스의 생성자에서 부모 클래스의 생성자를 호출하려면 super 키워드를 사용해야 한다. 이는 자식 클래스가 부모 클래스에서 정의된 속성을 상속받을 수 있도록 한다.

class Animal {
  constructor(name) {
    this.name = name;
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name); // 부모 클래스의 생성자를 호출하여 'name' 속성을 초기화합니다.
    this.breed = breed; // Dog 클래스의 고유 속성을 초기화합니다.
  }
}

const dog = new Dog('Rex', 'German Shepherd');
console.log(dog.name);  // "Rex"
console.log(dog.breed); // "German Shepherd"

부모 클래스의 메서드 호출

자식 클래스의 메서드에서 부모 클래스의 메서드를 호출할 수도 있다.

class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name);
    this.breed = breed;
  }

  speak() {
    super.speak(); // 부모 클래스의 speak 메서드를 호출합니다.
    console.log(`${this.name} barks.`);
  }
}

const dog = new Dog('Rex', 'German Shepherd');
dog.speak();
// "Rex makes a noise."
// "Rex barks."

메서드 오버라이딩(Method Overriding)

메서드 오버라이딩은 자식 클래스에서 부모 클래스의 메서드를 재정의하는 것을 의미한다. 자식 클래스에서 부모 클래스와 동일한 이름의 메서드를 정의하면, 자식 클래스의 메서드가 우선적으로 호출된다.

class Animal {
  speak() {
    console.log('Animal makes a noise.');
  }
}

class Dog extends Animal {
  speak() {
    console.log('Dog barks.');
  }
}

const animal = new Animal();
animal.speak(); // "Animal makes a noise."

const dog = new Dog();
dog.speak(); // "Dog barks."
  1. 프로퍼티(property)
    • 클래스 내부에서 선언된 변수를 의미한다. 최신 자바스크립트에서는 클래스 필드 문법을 통해 클래스 프로퍼티를 간편하게 선언할 수 있다.
class Car {
  // 클래스 필드
  brand = 'Toyota';

  constructor(model) {
    this.model = model;
  }

  getCarInfo() {
    return `${this.brand} ${this.model}`;
  }
}

const car = new Car('Corolla');
console.log(car.getCarInfo()); // "Toyota Corolla"

접근제어자

현재 자바스크립트에서는 클래스 내부의 필드를 private으로 선언할 수 있는 문법이 도입되었다. 이는 # 기호를 사용한다.

class Counter {
  #count = 0; // private 필드

  increment() {
    this.#count++;
  }

  getCount() {
    return this.#count;
  }
}

const counter = new Counter();
counter.increment();
console.log(counter.getCount()); // 1
console.log(counter.#count); // SyntaxError: Private field '#count' must be declared in an enclosing class

이러한 접근 제어자는 객체의 데이터 캡슐화(encapsulation)를 돕는다.

요약

자바스크립트의 클래스는 객체 지향 프로그래밍의 개념을 더 명확하고 구조적으로 표현할 수 있게 해주는 유용한 도구이다. 클래스와 객체의 사용을 통해 코드의 재사용성을 높이고, 코드의 가독성과 유지보수성을 개선할 수 있다. ES6의 클래스 문법을 잘 활용하면 자바스크립트에서도 강력한 객체 지향 프로그래밍을 구현할 수 있다.

0개의 댓글