Post

클래스(Class) 기본 개념

클래스

자바스크립트는 프로토타입 기반(prototype-based)의 객체지향 언어로 객체 간 상속프로토타입 체인 등을 활용하여 객체지향 프로그래밍을 구현합니다.

일반적인 객체지향 언어인 C++, Java와는 다르게 클래스가 존재하지 않지만 ES6 부터는 클래스의 개념의 도입으로 클래스 기반 객체지향 언어와 흡사한 형태를 갖추게 되었습니다.

기본 문법

클래스 선언을 위해서는 class 키워드와 클래스로 사용할 클래스의 이름이 필요합니다. 클래스의 이름은 일반적으로 파스칼 케이스를 사용하지만 사용하지 않아도 오류는 발생하지 않습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 클래스 선언문
class Rectangle {
  // 생성자
  constructor(parameters) {
    // 초기화 코드
  }

  // 메서드
  methodName(parameters) {
    // 메서드 코드
  }
  
  // 정적 메서드
  static staticMethodName(parameters) {
    // 정적 메서드 코드
  }
}

인스턴스 생성

클래스의 인스턴스를 생성하는 방법으로는 new 키워드를 사용하여 클래스의 생성자 함수를 호출하는 방법이 존재합니다.

여기서 인스턴스(Instance)는 클래스를 기반으로 메모리에 실제로 할당된 객체를 이야기합니다. 이러한 인스턴스를 통해 클래스의 변수에 접근하거나 메소드를 호출하는 등의 작업을 할 수 있습니다.

1
2
3
4
5
6
7
8
class Person {
    constructor(name) {
        this_.name = name;
    }
}

// 클래스 인스턴스 생성
const person = new Person("Park");

클래스 생성자

생성자(constructor)는 인스턴스가 생성 될 때 호출되는 메소드이며, 객체를 초기화하고 필요한 프로퍼티 값을 할당하는 역할을 합니다.

1
2
3
4
5
6
7
8
9
10
class Product {
  constructor(name, price) {
    this._name = name;
    this._price = price;
  }
}

const apple = new Person("apple", 1000);
console.log(apple._name); // "apple"
console.log(apple._price); // 1000

정적 메소드

정적 메소드는 클래스의 인스턴스를 생성하지 않고도 호출할 수 있는 메소드를 의미하며, 정적 메소드의 정의를 위해서는 static 키워드를 사용합니다.

1
2
3
4
5
6
7
8
9
10
class Area {
    static width = 10;
    static height = 5;
    
    static getArea() {
        console.log(this.width * this.height);
    }
};

Area.getArea(); // 50

정적 메소드는 클래스의 이름을 통해서만 호출할 수 있으며, 인스턴스로는 호출할 수 없다. 즉 정적 메소드는 this를 사용할 수 없다는 것을 의미한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Radius {
    constructor(radius) {
      this._radius = radius;
    }
  
    static staticRadiusMethod() {
      return Math.PI;
    }
}

console.log(Radius.staticRadiusMethod()); // 3.141592653589793

const rectangle = new Radius(5);
console.log(rectangle.staticRadiusMethod()); // Uncaught TypeError

getter, setter

gettersetter는 객체에서 프로퍼티에 접근하는 방법을 제어하기 위해 사용되는 메서드입니다.

getter

getter는 get 키워드를 사용하여 정의하며, 프로퍼티 이름 뒤에 따라오는 함수로 구현합니다. getter 함수는 해당 프로퍼티를 읽을 때 자동으로 호출되며, 반환된 값을 사용합니다.

1
2
3
4
5
6
7
8
9
10
11
12
class Person {
    constructor(name) {
        this._name = name;
    }
    
    get name() {
        return this._name;
    }
}

const person = new Person("kim");
console.log(person.name); // kim

setter

setter는 set 키워드를 사용하여 정의하며, 프로퍼티 이름 뒤에 따라오는 함수로 구현됩니다. setter 함수는 해당 프로퍼티에 값이 할당될 때 자동으로 호출되며, 전달된 값으로 프로퍼티를 설정합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Person {
    constructor(name) {
        this._name = name;
    }
    
    set setName(v) {
        if (typeof v === "string") {
            this._name = v;
        } else {
            console.log('Type mismatch.')
        }
    }
}

const person = new Person("kim");
person.setName = "park";
console.log(person); // Person { _name: 'park' }

person.setName = 100;
console.log(person); // Type mismatch.

클래스 필드 선언

기존에는 클래스 내부에 직접적으로 변수를 선언할 수 없었으며, 생성자 메서드 내부에서 속성을 초기화해야 했지만 최근에 기능이 추가되어 클래스 내부에 변수를 선언할 수 있게 되었습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Product {
    quantity = 0;
    
    constructor(name, price) {
        this._name = name;
        this._price = price;
    }
    
    getPrice() {
        return this._price * this.quantity; 
    }
}

const apple = new Product('apple', 1000);
apple.quantity = 5;
console.log(apple.getPrice()); // 5000

상속

상속은 하위에 존재하는 자식 클래스가 상위에 존재하는 부모 클래스생성자, 메소드, 프로토타입 체인 등을 이어 받는 것입니다.

즉, 자식 클래스는 상속을 통해 부모 클래스의 특성과 동작을 확장하고, 필요한 경우에는 재정의하여 다른 동작을 수행할 수 있습니다.

extends

extends 키워드는 부모 클래스를 상속 받는 자식 클래스를 정의할 때 사용하며, 아래의 예시는 Animal 클래스를 상속받는 Dog 클래스를 정의한 것입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// 부모 클래스
class Animal {
  constructor(name) {
    this._name = name;
  }

  getName() {
    console.log(this._name);
  }
}

// 자식 클래스
class Dog extends Animal {
  constructor(name, weight) {
    super(name);
    this._weight = weight;
  }

  getName() {
    console.log(`The animal's name is ${this._name}`);
  }

  getWeight() {
    console.log(this._weight);
  }
}

const andy = new Dog('andy', 55);
andy.getName(); // The animal's name is andy
andy.getWeight(); // 55

super

super 키워드는 자식 클래스에서 부모 클래스의 생성자에 접근하기 위해서 사용되며, 반드시 생성자의 1번째 줄에 호출되어야 합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Parent {
  constructor(name) {
    this._name = name;
  }

  get name() {
    return this._name;
  }
}

class Child extends Parent {
  constructor(name, age) {
    super(name);
    this._age = age;
  }

  get age() {
    return this._age;
  }
}

const child = new Child('Andrew', 28);
console.log(child.name); // Andrew
console.log(child.age); // 28


Reference

JAVASCRIPT.INFO: 클래스

MDN Web Docs: Classes

poiemaweb: 클래스

모던 자바스크립트 Deep Dive (자바스크립트의 기본 개념과 동작 원리)

This post is licensed under CC BY 4.0 by the author.