윤시의 블로그

[JavaScript] Class 본문

JavaScript

[JavaScript] Class

yo09 2025. 2. 27. 08:38

클래스란?

자바스크립트에서 클래스는 객체 지향 프로그래밍(OOP)을 지원하는 중요한 구조로, 객체 생성속성 및 메서드 정의를 보다 효율적으로 할 수 있게 해준다. 자바스크립트는 ES6(ECMAScript 2015)에서 class 문법을 도입했으며, 클래스는 객체를 생성하기 위한 템플릿(설계도) 역할을 한다.

자바스크립트 클래스의 기본 구성 요소

  1. class 키워드: 클래스를 정의하는데 사용된다.
  2. constructor: 클래스 인스턴스가 생성될 때 호출되는 메서드로, 객체 초기화에 사용된다.
  3. this: 클래스 내에서 자신을 가리키는 키워드로, 클래스 인스턴스의 속성 및 메서드에 접근하는 데 사용된다.

1. 클래스 정의하기

클래스 선언식

클래스를 정의할 때 class 키워드를 사용한다. 클래스 이름은 대문자로 시작하는 것이 일반적이다.

class Person {
  // 생성자(constructor)
  constructor(name, age) {
    this.name = name; // 인스턴스의 속성(name)을 설정
    this.age = age;   // 인스턴스의 속성(age)을 설정
  }

  // 메서드 정의
  greet() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

// 인스턴스 생성
const person1 = new Person('Alice', 25);
person1.greet(); // "Hello, my name is Alice and I am 25 years old."

설명

  • class Person: Person이라는 이름의 클래스를 정의한다.
  • constructor(name, age): constructor는 클래스의 인스턴스가 생성될 때 호출된다. this를 사용하여 인스턴스의 속성(name, age)을 설정한다.
  • greet(): 클래스 내에서 정의한 메서드로, 인스턴스의 속성에 접근하여 메시지를 출력한다.

2. constructor 메서드

constructor 메서드는 인스턴스가 생성될 때 자동으로 호출되는 특수한 메서드이다. 주로 객체 초기화 작업을 한다.

예제

class Car {
  constructor(make, model) {
    this.make = make;
    this.model = model;
  }

  displayInfo() {
    console.log(`${this.make} ${this.model}`);
  }
}

const myCar = new Car("Toyota", "Corolla");
myCar.displayInfo(); // "Toyota Corolla"
  • constructor(make, model): Car 클래스의 인스턴스가 생성될 때 make와 model 값을 받아 인스턴스 속성으로 설정한다.
  • this: this는 현재 인스턴스를 가리킨다. this.make와 this.model은 인스턴스의 속성으로, 클래스 외부에서 접근할 수 있다.

3. 클래스 메서드

클래스 내에서 정의된 메서드는 인스턴스에서 호출할 수 있다. 메서드는 this 키워드를 사용하여 클래스의 속성에 접근할 수 있다.

예제

class Dog {
  constructor(name, breed) {
    this.name = name;
    this.breed = breed;
  }

  bark() {
    console.log(`${this.name} says Woof!`);
  }
}

const dog1 = new Dog("Buddy", "Golden Retriever");
dog1.bark(); // "Buddy says Woof!"
  • bark(): Dog 클래스의 인스턴스인 dog1에서 호출할 수 있는 메서드이다. 이 메서드는 this.name을 사용하여 해당 인스턴스의 name 속성에 접근하고, 인스턴스마다 다른 이름을 출력한다.

4. 클래스 인스턴스화

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

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

  introduce() {
    console.log(`Hi, I am ${this.name} and I am ${this.age} years old.`);
  }
}

const person1 = new Person("John", 30);  // 새로운 인스턴스 생성
const person2 = new Person("Sarah", 28);

person1.introduce(); // Hi, I am John and I am 30 years old.
person2.introduce(); // Hi, I am Sarah and I am 28 years old.
  • new Person("John", 30): Person 클래스의 새로운 인스턴스를 생성하고, person1에 할당한다. person1은 "John"과 30을 속성으로 가진 객체가 된다.
  • person1.introduce()는 person1 인스턴스의 name과 age 속성을 출력한다.

5. 클래스 상속 (Inheritance)

자바스크립트 클래스에서는 상속을 통해 부모 클래스의 속성메서드자식 클래스가 물려받을 수 있다.

  • extends: 자식 클래스가 부모 클래스를 상속받을 때 사용한다.
  • super(): 부모 클래스의 생성자를 호출할 때 사용한다.

예제: 클래스 상속

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

  speak() {
    console.log(`${this.name} makes a sound`);
  }
}

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

  speak() {
    console.log(`${this.name} says Woof!`);
  }
}

const dog1 = new Dog("Buddy", "Golden Retriever");
dog1.speak(); // "Buddy says Woof!"
  • Dog extends Animal: Dog 클래스는 Animal 클래스를 상속받아, Animal 클래스의 name 속성 및 speak 메서드를 물려받는다.
  • super(name): 부모 클래스인 Animal의 생성자를 호출하여 name을 초기화한다.
  • speak(): 자식 클래스에서 부모 메서드를 재정의(오버라이딩) 하여, Dog 인스턴스에 맞는 동작을 정의한다.

6. 정적 메서드 (Static Methods)

클래스에는 정적 메서드를 정의할 수 있다. 정적 메서드는 인스턴스를 생성하지 않고 클래스 자체에서 호출할 수 있는 메서드이다.

예제: 정적 메서드

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

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

console.log(MathUtils.add(3, 4)); // 7
console.log(MathUtils.multiply(3, 4)); // 12
  • static: add와 multiply 메서드는 정적 메서드로 정의되어, MathUtils 클래스를 통해 직접 호출할 수 있다.
  • 정적 메서드는 인스턴스를 생성하지 않고 클래스에서 바로 호출할 수 있다.

7. 클래스 필드 (Class Fields)

클래스 필드는 클래스 내부에서 선언된 속성으로, 인스턴스를 생성할 때 해당 속성의 값을 초기화할 수 있다.

예제: 클래스 필드

class Person {
  name = "John";  // 클래스 필드
  age = 30;

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

  introduce() {
    console.log(`Hi, I am ${this.name} and I am ${this.age} years old.`);
  }
}

const person1 = new Person("Alice", 25);
person1.introduce(); // "Hi, I am Alice and I am 25 years old."
  • 클래스 필드는 클래스 내에서 직접 선언하며, 생성자에서 값을 설정할 수 있다.
  • 위 예제에서는 name과 age 속성이 클래스 필드로 선언된다.

클래스 선언과 사용

class Animal {

constructor(name, sound) { *// 생성자 메서드는 객체를 초기화한다.*

this.name = name;

this.sound = sound;

}

makeSound() { *// 메서드는 클래스의 동작을 정의한다.*

console.log(`${this.name} says ${this.sound}`);

}

}

const cat = new Animal("Cat", "Meow");

cat.makeSound(); *// Cat says Meow*

• class 키워드로 클래스를 선언한다.

• constructor는 객체를 초기화하는 메서드로, 클래스 내에 반드시 한 번만 선언된다.

• 메서드는 객체의 동작(함수)을 정의하며, 클래스의 prototype에 추가된다.

클래스 상속

class Dog extends Animal { *// Animal 클래스를 상속받는다.*

constructor(name, sound, breed) {

super(name, sound);    *// 부모 클래스의 생성자를 호출한다.*

this.breed = breed;

}

showBreed() { *// 자식 클래스에서 새로운 메서드를 추가한다.*

console.log(`Breed: ${this.breed}`);

}

}

const dog = new Dog("Dog", "Woof", "Golden Retriever");

dog.makeSound(); *// Dog says Woof*

dog.showBreed(); *// Breed: Golden Retriever*

• extends 키워드는 부모 클래스를 상속받는 데 사용된다.

• super는 부모 클래스의 생성자나 메서드를 호출하는 데 사용된다.

정적 메서드와 속성

class MathUtils {

static add(a, b) { *// 정적 메서드는 클래스 자체에서 호출 가능하다.*

return a + b;

}

}

console.log(MathUtils.add(3, 7)); *// 10*

정적 메서드는 객체를 생성하지 않고 클래스 이름으로 바로 호출할 수 있는 메서드이다.