minstudio

클래스 (Class) 와 객체 지향 프로그래밍

클래스(Class)는 ES6에 도입된 객체 생성 템플릿입니다. 자바스크립트는 본래 프로토타입(Prototype) 기반 언어이지만, Java나 C++ 같은 다른 언어 개발자들에게 익숙한 객체 지향 문법(Syntactic Sugar)을 제공하기 위해 만들어졌습니다.

constructor로 초기 데이터를 셋업하고, 메서드를 정의하며, extends 키워드로 다른 클래스를 쉽게 상속받아 코드를 재사용할 수 있습니다.

🏗️ Class 상속 구조 Animal (부모) name (속성) speak() extends Dog (자식) speak() -> "멍멍!" (오버라이딩)
<script>
// 부모 클래스 정의
class Animal {
  constructor(name) {
    this.name = name; // 객체가 생성될 때 초기화됨
  }

  speak() {
    console.log(`${this.name}이(가) 소리를 냅니다.`);
  }
}

// 자식 클래스가 부모를 상속 (extends)
class Dog extends Animal {
  constructor(name, breed) {
    super(name); // 부모의 constructor를 먼저 호출해야 함!
    this.breed = breed;
  }

  // 메서드 오버라이딩 (부모의 기능을 덮어씀)
  speak() {
    console.log(`${this.name}(${this.breed})이(가) 멍멍! 짖습니다.`);
  }
}

console.log("=== Class 객체 생성 ===");
const genericAnimal = new Animal("동물");
genericAnimal.speak();

const myDog = new Dog("바둑이", "골든 리트리버");
myDog.speak(); // 오버라이딩된 메서드 실행
</script>
실행 결과
클래스 (Class) 와 객체 지향 프로그래밍 | Minstudio