Javascript

[Javascript] 자바스크립트 Class / Getter&Setter / Extends 정리

하부루 2025. 3. 30. 14:34

Class(클래스)란?

클래스는 객체를 만들기 위한 틀(설계도)이다.
즉, 공통된 특징을 가진 객체들을 효율적으로 만들기 위해 사용한다.

 

붕어빵 틀 = 클래스 (공통된 구조)
붕어빵 = 객체(인스턴스) (틀을 이용해 찍어낸 실체)

 

예를 들어, 클래스를 사용해서 사람(Person)을 표현해보자

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

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

const person1 = new Person("Kim", 20);
const person2 = new Person("Lee", 30);

person1.speak(); // Kim says hello!
person2.speak(); // Lee says hello!

 

여기서 Person이라는 클래스는 사람을 표현하는 공통 구조이고, person1, person2는 각각 실제 사람(객체)이다.

 

만약 클래스 없이 객체를 만든다면 ?

const person1 = {
  name: "Kim",
  age: 20,
  speak: function () {
    console.log(this.name + " says hello!");
  }
};

 

이런 식으로 만들 수도 있지만, 여러개의 객체를 만들자고 할 때 코드에 중복이 생기고 매우 불편하다. 그래서 만들어진 것이 클래스이다.

 

Class(클래스)에서 Constructor란?

constructor()는 클래스에서 객체가 생성될 때 자동으로 호출되는 특수한 메서드이다.
즉, 우리가 new 키워드를 사용해서 클래스로부터 객체를 만들 때, 가장 먼저 실행되는 함수이다.

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

위 예제코드에서 constructor(name, age)는 Person 클래스의 생성자이다.
이 생성자를 통해 name과 age라는 속성을 객체에 설정할 수 있다.

const person = new Person("Kim", 20);
console.log(person.name); // "Kim"
console.log(person.age);  // 20

 

왜 Constructor를 사용할까?

1. 객체 초기화
-> 객체가 생성될 때, 필요한 값을 설정하는 초기화 용도로 사용한다.

const person1 = new Person("Kim", 20); // 생성과 동시에 속성 설정

2. 클래스마다 다른 속성을 가진 객체 생성 가능
-> 같은 Person 클래스지만 각각 다른 속성을 가진 객체를 만들 수 있다.

const person2 = new Person("Lee", 30);
const person3 = new Person("Park", 25);

3. 중복 제거
→ 반복적인 초기화 코드를 줄여주고, 클래스 내부에서 관리 할 수 있다.

// constructor가 없다면 매번 이렇게 해야 함
const person = {};
person.name = "Kim";
person.age = 20;

 

Class(클래스)의 장점

  • 객체를 쉽게 찍어내기 가능 (코드 재사용)
  • 구조화된 코드 작성 가능
  • 유지보수하기 편하다
  • 상속, 캡슐화, 다형성 같은 객체지향 특징 사용 가능

 

Getter와 Setter 함수

  • getter: 속성에 접근할 때 자동으로 호출되는 함수(읽기만 가능한 속성으로 만들 수 있음)
  • setter: 속성에 값을 할당할 때 자동으로 호출되는 함수(잘못된 값이 설정되는 상황을 방지)
class User {
    constructor(firstName, lastName, age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age; // setter 호출됨
    }

    get age() {
        return this._age;
    }

    set age(value) {
        if (value < 0) {
            console.log("나이는 음수가 될 수 없습니다.");
            this._age = 0;
        } else {
            this._age = value;
        }
    }
}
const user1 = new User("lee", "jhin", 25);
console.log(user1.age) // 25

const user2 = new User("Kim", "munsoo", -5);
console.log(user2.age); // 0

 

Extends : 클래스 상속

extends는 다른 클래스를 상속하여 속성과 메서드를 재사용할 수 있게 해주는 키워드이다.
즉, 자식 클래스가 부모 클래스의 기능을 물려받을 수 있다.

// 부모 클래스
class Shape {
    constructor(width, height, color) {
        this.width = width;
        this.height = height;
        this.color = color;
    }

    draw() {
        console.log(`Drawing ${this.color} shape`);
    }

    getArea() {
        return this.width * this.height;
    }
}

// 자식 클래스 (기능 그대로 상속)
class Rectangle extends Shape {}

// 자식 클래스 (메서드 오버라이딩)
class Triangle extends Shape {
    draw() {
        super.draw(); // 부모의 draw()도 실행
        console.log(`Drawing triangle with color ${this.color}`);
    }

    getArea() {
        return (this.width * this.height) / 2;
    }
}

// 사용 예시코드
const rect = new Rectangle(10, 20, "blue");
rect.draw();                 // Drawing blue shape
console.log(rect.getArea()); // 200

const tri = new Triangle(10, 20, "red");
tri.draw();     // Drawing red shape

console.log(tri.getArea()); // 100

 

  • Rectangle은 Shape 클래스를 상속받아 draw(), getArea()를 그대로 사용한다.
  • Triangle은 Shape를 상속받되, draw()와 getArea() 메서드를 오버라이딩하여 기능을 확장하고있다.
  • super 키워드를 사용하면 부모 클래스의 생성자나 메서드를 호출할 수 있다.

 

마무리 정리

Class는 객체를 쉽고 효율적으로 생성하는 방법이고, 자바스크립트를 더 구조적으로 사용할 수 있게 도와주는 핵심 개념이다.

그리고 그 클래스 내부에서 constructor, getter, setter, extends 같은 기능들을 활용하면, 객체를 더 다양하게 사용할 수 있다.

 

  • class는 객체를 정의하고 확장하는 틀
  • constructor()는 객체 초기화를 담당
  • getter/setter는 속성의 접근/설정을 논리적으로 제어
  • extends는 코드 재사용과 유연한 확장을 가능하게 해준다.