[JavaScript] 클래스(class)

HyeJean·2024년 4월 4일

JavaScript

목록 보기
12/13

자바와 C++을 배울 때 익혔던 클래스랑 뭐가 다른건지 궁금한 상태로 강의를 봤는데 대충 비슷한 거 같은데 복잡하게 풀어서 설명해주는 거 같아서 더 헷갈리게 되었다 하하

🤔 자바스크립트 클래스

 클래스는 객체 생성을 위한 틀이다. 빠질 수 없는 붕어빵이야기... 클래스는 붕어빵 기계(틀)이고 틀을 통해서 찍어 만들어 낸 결과인 붕어빵 자체가 객체가 된다.

프로토타입 기반 언어인 자바스크립트에 클래스가 도입된 이유는 아래와 같다.

① 문법적 편의성
클래스 문법은 기존의 프로토타입 문법보다 더 직관적인 객체 지향 프로그래밍 스타일을 갖는다. 즉.. 프로토타입보다 코드 작성이 쉽다.

② 가독성 및 유지보수성 향상
클래스 문법은 코드의 가독성을 향상시켜주고, 객체 간의 관계 표현이 직관적이다. 직관적인 표현은 코드의 유지보수성을 높인다.

③ ES6의 다른 기능과의 호환성
ES6에서는 클래스 문법뿐만 아니라 화살표 함수, let, const 변수 선언, 템플릿 리터럴 등의 여러 기능이 도입되었다. 클래스 문법은 다른 ES6 기능과의 호환성을 높인다.


 클래스를 생성하면 prototype 속성에 객체가 생성되고, 이 객체는 생성되는 모든 인스턴스의 프로토타입이 된다. 인스턴스는 프로토타입에서 속성과 메서드를 상속받는다.



🔍 ES6 이전의 클래스

⭐ 생성자 함수(Constructor Function)

 클래스를 생성하기 위해 생성자 함수를 사용했다.

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

const person1 = new Person("Megumi", 26);

⭐ 프로토타입(Prototype)

 생성자 함수로 생성된 객체는 프로토타입 체인을 통해 메서드나 속성을 상속받았다. 모든 객체는 부모 프로토타입 객체를 가진다.

Person.prototype.greet = function() {
  return `My name is ${this.name}`;
};

console.log(person1.greet()); // My name is Megumi

⭐ 상속(Inheritance)

 부모 생성자 함수의 프로토타입을 자식 생성자 함수의 프로토타입으로 설정하여 상속을 구현했다.

function Student(name, age, grade) {
  // 부모 생성자 호출
  Person.call(this, name, age);
  this.grade = grade;
}

// 상속 설정
Student.prototype = new Person();
Student.prototype.constructor = Student;

Student.prototype.study = function() {
  return `${this.name} is studying`;
};

const student1 = new Student("HyeJean", 26, "A");
console.log(student1.greet()); // My name is HyeJean
console.log(student1.study()); // HyeJean is studying


🔍 ES6의 클래스

⭐ 클래스 선언

 클래스는 class 키워드를 사용하여 선언한다.

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

  greet() {
    return `My name is ${this.name}.`;
  }
}

⭐ 생성자(Constructor)

 클래스 내부에 constructor 메서드를 정의하여 객체를 초기화한다. 객체 생성 시 자동 호출된다.

⭐ 메서드(Methods)

 클래스 내부에 메서드 정의가 가능하다. 메서드는 클래스의 프로토타입에 할당된다.

⭐ 정적 메서드(Static Methods)

 클래스 내부에 static 키워드를 사용하여 정적 메서드 정의가 가능하다. 정적 메서드는 인스턴스 객체가 아닌 클래스 자체에 속한다.

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

console.log(Calculator.add(1, 2)); // 3

⭐ 상속(Inheritance)

 extends 키워드를 사용하여 다른 클래스를 상속받을 수 있다. 부모 클래스의 생성자 호출은 super 키워드를 사용한다.

class Student extends Person {
  constructor(name, age, grade) {
    super(name, age);
    this.grade = grade;
  }

  study() {
    return `${this.name} is studying`;
  }
}

⭐ 접근자(Accessors)

 gettersetter 메서드를 사용하여 객체의 속성 활용이 가능하다.

class Circle {
  constructor(radius) {
    this._radius = radius;
  }

  get radius() {
    return this._radius;
  }

  set radius(value) {
    this._radius = value;
  }
}


🔍 클래스를 사용하는 이유

  • 사용자 정의 객체 생성
    동일한 기능을 가진 여러 객체를 쉽게 생성할 수 있다.

  • 코드 재사용
    코드를 중복 작성하지 않고 여러 번 활용할 수 있다.

  • 코드 관리 및 유지 보수
    코드의 체계적인 관리와 유지 보수가 쉽다.

  • 객체 지향 프로그래밍
    상속, 추상화, 인터페이스 등 객체 지향 프로그래밍의 개념을 활용할 수 있다.

0개의 댓글