본문 바로가기
JavaScript 문법 시리즈

[JavaScript 문법] 12일차: ES6 클래스

by cogito21_js 2024. 8. 12.
반응형

클래스란?

클래스는 객체 지향 프로그래밍의 기본 단위로, 객체를 생성하기 위한 템플릿입니다. ES6에서는 객체 지향 프로그래밍을 더 쉽게 구현할 수 있도록 class 문법이 도입되었습니다.

클래스 선언

클래스는 class 키워드를 사용하여 선언할 수 있습니다.

 

기본 문법

class 클래스이름 {
  constructor(매개변수1, 매개변수2, ...) {
    // 초기화 코드
  }

  메서드이름() {
    // 메서드 코드
  }
}

예제

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log('Hello, my name is ' + this.name);
  }
}

let person1 = new Person('Alice', 25);
let person2 = new Person('Bob', 30);

person1.greet(); // 'Hello, my name is Alice'
person2.greet(); // 'Hello, my name is Bob'

 

클래스 표현식

클래스는 표현식으로도 정의할 수 있습니다. 클래스 표현식은 익명 또는 이름을 가질 수 있습니다.

 

예제: 익명 클래스 표현식

let Person = class {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log('Hello, my name is ' + this.name);
  }
};

let person1 = new Person('Alice', 25);
person1.greet(); // 'Hello, my name is Alice'

 

예제: 이름을 가진 클래스 표현식

let Person = class PersonClass {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log('Hello, my name is ' + this.name);
  }
};

let person1 = new Person('Alice', 25);
person1.greet(); // 'Hello, my name is Alice'

클래스 상속

클래스 상속을 통해 다른 클래스를 기반으로 새로운 클래스를 정의할 수 있습니다. extends 키워드를 사용하여 상속을 구현합니다.

 

기본 문법

class 자식클래스 extends 부모클래스 {
  constructor(매개변수1, 매개변수2, ...) {
    super(매개변수1, 매개변수2, ...);
    // 초기화 코드
  }

  자식메서드이름() {
    // 메서드 코드
  }
}

 

예제

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

  makeSound() {
    console.log(this.type + ' makes a sound');
  }
}

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

  bark() {
    console.log(this.name + ' says Woof! Woof!');
  }
}

let myDog = new Dog('Buddy');
myDog.makeSound(); // 'Dog makes a sound'
myDog.bark(); // 'Buddy says Woof! Woof!'

정적 메서드

정적 메서드는 인스턴스화된 객체가 아닌 클래스 자체에서 호출되는 메서드입니다. static 키워드를 사용하여 정의합니다.

 

예제

class MathUtil {
  static add(a, b) {
    return a + b;
  }
}

console.log(MathUtil.add(2, 3)); // 5

getter와 setter

getter와 setter는 클래스의 속성을 간편하게 접근하고 수정할 수 있도록 합니다. getset 키워드를 사용하여 정의합니다.

 

예제

class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }

  get area() {
    return this.width * this.height;
  }

  set area(value) {
    this.width = value / this.height;
  }
}

let rect = new Rectangle(10, 2);
console.log(rect.area); // 20

rect.area = 40;
console.log(rect.width); // 20

클래스 필드

클래스 필드는 클래스의 인스턴스가 아닌, 클래스 자체의 속성을 정의합니다. 아직 모든 환경에서 표준화된 기능은 아니지만, 최신 자바스크립트에서는 사용할 수 있습니다.

 

예제

class Circle {
  radius = 0;

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

  getDiameter() {
    return this.radius * 2;
  }
}

let circle = new Circle(5);
console.log(circle.getDiameter()); // 10

클래스 상속과 메서드 오버라이딩

메서드 오버라이딩을 통해 부모 클래스의 메서드를 자식 클래스에서 재정의할 수 있습니다.

 

예제

class Animal {
  makeSound() {
    console.log('Some generic animal sound');
  }
}

class Dog extends Animal {
  makeSound() {
    console.log('Woof! Woof!');
  }
}

let genericAnimal = new Animal();
genericAnimal.makeSound(); // 'Some generic animal sound'

let myDog = new Dog();
myDog.makeSound(); // 'Woof! Woof!'

결론

ES6 클래스는 JavaScript에서 객체 지향 프로그래밍을 구현하기 위한 강력한 도구입니다. 이번 글에서는 클래스 선언, 클래스 표현식, 클래스 상속, 정적 메서드, getter와 setter, 클래스 필드, 클래스 상속과 메서드 오버라이딩에 대해 배웠습니다. 다음 글에서는 맵과 셋에 대해 알아보겠습니다.

다음 글에서 만나요!

 

반응형