[웹 개발 기초 자바스크립트] 13. ES6 Classes

Shy·2023년 8월 30일
0

NodeJS(Express&Next.js)

목록 보기
14/39

ECMASCript6 (ES6)

ES6에서 나온 Class를 이용해서 더 쉽게 OOP를 구현할 수 있다.

ECMAScript 6 (ES6), 또는 ECMAScript 2015,는 JavaScript 언어의 중요한 업데이트 중 하나이다. 이 업데이트에서는 클래스(class) 문법이 도입되어, 객체 지향 프로그래밍이 더 쉽고 명확해졌다. ES6 클래스는 Java, C#, 그리고 다른 객체 지향 언어에서 볼 수 있는 것과 유사한 클래스 기반의 객체 지향 프로그래밍을 JavaScript에서 구현할 수 있게 해준다.

기존의 프로토타입 기반 상속은 복잡하고 이해하기 어려울 수 있었는데, ES6 클래스는 이를 보다 간결하고 이해하기 쉬운 문법으로 대체한다.

클래스 선언

기본 문법은 다음과 같다.

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  greet() {
    console.log(`Hello, my name is ${this.name}.`);
  }
}

인스턴스 생성

new 키워드를 사용하여 클래스의 인스턴스를 생성할 수 있다.

const john = new Person('John', 30);
john.greet();  // Output: Hello, my name is John.

상속

extends 키워드를 사용하여 클래스를 상속할 수 있다.

class Student extends Person {
  constructor(name, age, grade) {
    super(name, age);
    this.grade = grade;
  }
  
  greet() {
    console.log(`Hello, my name is ${this.name} and I'm in grade ${this.grade}.`);
  }
}

const jane = new Student('Jane', 20, 'A');
jane.greet();  // Output: Hello, my name is Jane and I'm in grade A.

메서드 오버라이딩

상속받은 메서드를 자식 클래스에서 재정의(오버라이딩)할 수 있다. 위의 Student 클래스에서 greet 메서드가 오버라이딩 되었다.

ES6 클래스는 사실 프로토타입을 기반으로 동작한다. 즉, ES6 클래스는 단순히 프로토타입 기반 상속을 보다 쉽게 구현하기 위한 문법적 설탕(syntactic sugar)이다.

Static

"prototype"이 아닌 클래스 함수 자체에 메서드를 설정할 수도 있다. 이런 메서드를 정적(static)메서드 라고 한다.

JavaScript의 ES6 클래스에서 static 키워드는 해당 클래스에 속한 정적(static) 메서드를 정의할 때 사용된다. 정적 메서드는 클래스의 인스턴스를 생성하지 않고도 클래스 이름을 통해 호출할 수 있는 메서드이다. 이런 메서드는 주로 유틸리티 함수를 구현하거나, 인스턴스가 아닌 클래스 자체에 연산을 수행할 때 사용된다.

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

  static multiply(a, b) {
    return a * b;
  }
}

console.log(MathUtility.add(5, 3));  // 출력: 8
console.log(MathUtility.multiply(5, 3));  // 출력: 15

MathUtility 클래스에는 add와 multiply라는 두 개의 정적 메서드가 정의되어 있다. 이 메서드들은 클래스의 인스턴스를 생성하지 않고도 직접 호출할 수 있다.

정적 속성

ES6 이후의 버전에서는 정적 속성도 지원하고 있다. 이는 클래스 레벨에서 사용되는 변수를 정의할 수 있게 해준다.

class MyClass {
  static myStaticProperty = "someValue";
}

console.log(MyClass.myStaticProperty);  // 출력: "someValue"

주의점

  • 정적 메서드 내에서는 this 키워드가 클래스 자체를 가리킨다. 따라서 인스턴스의 속성이나 메서드에 접근할 수 없다.
  • 정적 메서드는 상속이 가능하다. 즉, 하위 클래스에서 super 키워드를 사용하여 부모 클래스의 정적 메서드를 호출할 수 있다.

정적 메서드와 속성은 객체 지향 프로그래밍에서 종종 유틸리티 함수나 상수 등을 구현할 때 유용하게 사용된다.

예제

예제1

class Person {
  constructor(name, email, birthday) {
    this.name = name;
    this.email = email;
    this.birthday = new Date(birthday);
  }

  introduce() {
    return `Hello, my name is ${this.name}.`;
  }
}

const john = new Person('John', 'john@abc.com', '10-3-98');

console.log(john);

에제2 (static)

class Person {
  constructor(name, email, birthday) {
    this.name = name;
    this.email = email;
    this.birthday = new Date(birthday);
  }
  
  introduce() {
    return `Hello my name is ${this.name}`;
  }
  
  static multipleNumvers(x, y) {
    return x * y
  }
}
Person.multipleNumvers(3, 4); // 12
profile
초보개발자. 백엔드 지망. 2024년 9월 취업 예정

0개의 댓글