
오늘은 JavaScript의 Class의 개념에 대해서 알아보고, 코드를 보며 Class에 대한 이해를 키워보려고 한다!
클래스는 "비슷한 물건을 찍어내는 공장"과 같은 것이다.
예를 들어, 자동차 공장은 동일한 설계도를 기반으로 색깔이나 옵션만 살짝 다른 여러 자동차를 만들 수 있다. 클래스는 바로 이런 설계도 또는 틀 역할을 한다.
그리고 이 설계도를 기반으로 만들어진 자동차 한 대 한 대가 바로 객체가 되는 것이다.
한 마디로, 클래스는 속성(데이터)과 메서드(동작)를 묶어두는 공장 설계도인 것이다.
JavaScript의 class는 이런 구조를 편하게 만들 수 있도록 도와주는 도구라고 생각하면 된다.
요약해서 말하자면 이유는 다음과 같다
- 반복 작업 최소화: 비슷한 객체를 쉽게 생성할 수 있음
- 구조화된 코드: 속성과 메서드를 한 곳에 묶어 가독성과 유지보수성을 높임
- 상속과 확장: 기존 클래스를 확장해 재사용성과 유연성 극대화
- 객체 지향 설계: 더 체계적이고 확장 가능한 코드 작성이 가능
추가로 JavaScript에서 class가 왜 생겨났는지를 말해보자면,
JS에서도 객체를 효율적으로 관리하기 위한 방법이 필요했고, 이를 위해 class라는 문법이 도입된 것 이다.
클래스의 구성 요소는 다음과 같다
- Constructor(생성자) : 객체를 초기화 하는 역할
- Properties(속성) : 객체가 가지는 데이터
- Methods(메서드) : 객체가 수행할 수 있는 동작
- Static Methods : 클래스 자체에서 호출되는 메서드
- Private Fields : 외부에서 접근할 수 없는 데이터
class Student {
constructor(name, age, grade) {
this.name = name; // 속성
this.age = age;
this.grade = grade;
}
introduce() { // 메서드
console.log(`안녕하세요, 저는 ${this.grade}학년 ${this.name}입니다.`);
}
}
const student1 = new Student("지민", 16, 10);
student1.introduce(); // 출력: 안녕하세요, 저는 10학년 지민입니다.
기본적인 클래스 구조
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name}가 소리를 냅니다.`);
}
}
const cat = new Animal("고양이");
cat.speak(); // 고양이가 소리를 냅니다.
상속을 통해 기존 클래스의 기능을 확장
class Dog extends Animal {
speak() {
console.log(`${this.name}가 멍멍 짖습니다.`);
}
}
const dog = new Dog("강아지");
dog.speak(); // 강아지가 멍멍 짖습니다.
객체가 아닌 클래스 자체에서 호출할 수 있는 메서드
class Calculator {
static add(a, b) {
return a + b;
}
}
console.log(Calculator.add(5, 3)); // 출력: 8
외부에서 직접 접근할 수 없는 클래스 속성
class BankAccount {
#balance = 0; // Private Field
deposit(amount) {
this.#balance += amount;
console.log(`현재 잔액: ${this.#balance}원`);
}
}
const account = new BankAccount();
account.deposit(1000); // 현재 잔액: 1000원
console.log(account.#balance); // Error: Private field cannot be accessed
문제
Car클래스를 작성하라.
- 속성: 브랜드(brand), 색상(color), 속도(speed)
- 메서드: 속도를 올리는 accelerate()와 속도를 줄이는 brake()
class Car {
constructor(brand, color) {
this.brand = brand;
this.color = color;
this.speed = 0;
}
accelerate(amount) {
this.speed += amount;
console.log(`${this.brand}가 ${amount}만큼 속도를 올립니다. 현재 속도: ${this.speed}`);
}
brake(amount) {
this.speed -= amount;
console.log(`${this.brand}가 ${amount}만큼 속도를 줄입니다. 현재 속도: ${this.speed}`);
}
}
const car = new Car("Tesla", "red");
car.accelerate(20); // Tesla가 20만큼 속도를 올립니다. 현재 속도: 20
car.brake(5); // Tesla가 5만큼 속도를 줄입니다. 현재 속도: 15