JavaScript

[JS] 코딩테스트 012 - Class 클래스

Irene1988 2025. 2. 16. 18:42

이 클래스가 상당히 헷갈린다.

휴~~~ JAVA에서는 클래스라는게 그냥 받아들였는데 이상하게 JS에서는 어렵게 느껴진다.

그래도 기회가 된 김에 다시 개념을 잡자!

 

문제12 : 게임 캐릭터 클래스 만들기
다음 소스코드에서 클래스를 작성하여 게임 캐릭터의 능력치와 '파이어볼'이 출력되게 만드시오.
주어진 소스 코드를 수정해선 안됩니다.


const x = new Wizard(545, 210, 10);
console.log(x.health, x.mana, x.armor);
x.attack();

/*
출력
545 210 10
파이어볼
 * 
 */

 

정답

class Wizard {
    constructor(health, mana, armor){
        this.health = health;
        this.mana = mana;
        this.armor = armor;
    }

    attack(){
        console.log("파이어볼");
    }
}

🔹 자바스크립트에서 class란?

자바스크립트에서 class는 객체를 생성하기 위한 템플릿.
ES6(ECMAScript 2015)부터 도입되었으며, 기존의 프로토타입 기반 상속을 더 직관적으로 사용할 수 있도록 만든 문법.

 

class 없이 객체 만드는 방식 (생성자 함수)

클래스가 없던 시절에는 생성자 함수를 사용해서 객체를 만들었다.

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

Person.prototype.greet = function() {
  console.log(`안녕! 나는 ${this.name}이야.`);
};

const person1 = new Person("철수", 25);
console.log(person1.name);  // "철수"
person1.greet();           // "안녕! 나는 철수이야."

 

👉 Person은 생성자 함수이고, prototype을 사용해서 메서드를 추가해야 했음
이렇게 하면 객체를 생성할 때 매번 같은 greet() 함수를 생성하지 않아도 되는 장점이 있다.

하지만... 코드가 직관적이지 않음. 그래서 등장한 게 class 문법! 🎉

 

🔹 ES6 class 문법

class 문법을 사용하면 코드가 더 깔끔해지고 가독성이 좋아져!

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

  greet() {
    console.log(`안녕! 나는 ${this.name}이야.`);
  }
}

const person2 = new Person("영희", 28);
console.log(person2.name); // "영희"
person2.greet();          // "안녕! 나는 영희이야."

👉 기존의 생성자 함수 방식과 결과는 같지만, 코드가 훨씬 직관적이고 깔끔해짐.


🔹 클래스의 주요 개념

1️⃣ 생성자 (constructor)

 

  • constructor는 객체가 생성될 때 자동으로 실행되는 함수
  • this를 사용해서 객체의 속성을 초기화.

 

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

  makeSound() {
    console.log(`${this.type}가(이) ${this.sound} 소리를 냅니다!`);
  }
}

const dog = new Animal("강아지", "멍멍");
dog.makeSound(); // "강아지가(이) 멍멍 소리를 냅니다!"

2️⃣ 클래스 상속 (extends)

 

  • extends 키워드를 사용하면 부모 클래스의 기능을 그대로 물려받을 수 있다.
  • 자식 클래스에서 super()를 사용해서 부모 클래스의 생성자 호출 가능.

 

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

  makeSound() {
    console.log(`${this.name}가 소리를 낸다!`);
  }
}

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

  bark() {
    console.log(`${this.name} (${this.breed})가 멍멍! 짖어요!`);
  }
}

const myDog = new Dog("바둑이", "시바견");
myDog.makeSound(); // "바둑이가 소리를 낸다!"
myDog.bark();      // "바둑이 (시바견)가 멍멍! 짖어요!"

👉 Dog 클래스는 Animal 클래스를 상속받아서 추가 기능을 구현할 수 있어!


3️⃣ 정적 메서드 (static)

 

  • static 키워드를 사용하면 클래스 자체에서 호출할 수 있는 메서드가 됨
  • 객체를 만들지 않아도 사용할 수 있음
class MathUtil {
  static add(a, b) {
    return a + b;
  }
}

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

 

👉 MathUtil.add(5, 3)처럼 객체를 생성하지 않고 바로 사용 가능!


4️⃣ 게터(getter) & 세터(setter)

 

  • get: 특정 속성을 조회할 때 추가 로직을 실행할 수 있음.
  • set: 속성 값을 설정할 때 제어할 수 있음.
class User {
  constructor(name) {
    this._name = name;  // 언더스코어(_)를 붙여 내부 변수로 사용
  }

  get name() {
    return this._name.toUpperCase();  // 대문자로 변환하여 반환
  }

  set name(newName) {
    if (newName.length < 2) {
      console.log("이름은 최소 2글자 이상이어야 합니다.");
      return;
    }
    this._name = newName;
  }
}

const user = new User("철수");
console.log(user.name); // "철수" → "철수" (대문자로 변환됨)

user.name = "영";  // "이름은 최소 2글자 이상이어야 합니다."
user.name = "영희";  
console.log(user.name); // "영희" → "영희"

 

👉 getter와 setter를 사용하면 속성을 안전하게 제어할 수 있다.


🔹 정리

class는 객체를 만들기 위한 템플릿
constructor를 사용해 속성 초기화
extends로 상속 가능 (super()로 부모 생성자 호출)
static 메서드는 인스턴스 없이 클래스에서 직접 호출 가능
getter & setter를 사용해 속성을 제어 가능

 

 

*위 포스팅은 챗GPT 답변을 바탕으로 작성되었습니다.