자바스크립트의 클래스
이 기사에서는 자바스크립트의 클래스에 대해 설명합니다.
YouTube Video
자바스크립트의 클래스
자바스크립트에서 클래스는 객체 지향 프로그래밍의 개념을 포함하며 객체의 청사진 역할을 합니다. 클래스를 사용하면 객체의 속성과 메서드를 간결하게 정의할 수 있어 재사용성과 코드 구조를 개선할 수 있습니다. 클래스 구문은 ES6에서 자바스크립트에 도입되었습니다.
클래스 정의
클래스는 class
키워드를 사용하여 정의되며 일반적으로 생성자라는 메서드로 초기화됩니다.
1class Person {
2 // Constructor method (called when the class is instantiated)
3 constructor(name, age) {
4 this.name = name; // Property definition
5 this.age = age;
6 }
7
8 // Method definition
9 greet() {
10 return `Hello, my name is ${this.name}`;
11 }
12}
13
14// Instantiation of the class
15const alice = new Person("Alice", 25);
16console.log(alice.greet()); // Hello, my name is Alice
class Person
으로 클래스를 정의합니다.constructor
는 객체가 생성될 때 자동으로 호출되는 특수한 메서드입니다.this
키워드는 클래스 내부에서 해당 클래스의 인스턴스(객체)를 나타냅니다.
클래스 속성과 메서드
클래스는 속성과 메서드를 정의할 수 있습니다. 속성은 객체의 특성을 나타내고, 메서드는 객체가 가지는 기능을 나타냅니다.
1class Car {
2 constructor(brand, model) {
3 this.brand = brand;
4 this.model = model;
5 }
6
7 // Method definition
8 drive() {
9 console.log(`Driving a ${this.brand} ${this.model}`);
10 }
11}
12
13const car1 = new Car("Toyota", "Corolla");
14car1.drive(); // Driving a Toyota Corolla
이 예제에서는 Car
클래스가 brand
와 model
속성, 그리고 drive
메서드로 선언되었습니다.
클래스 상속
클래스는 다른 클래스에서 상속받을 수 있습니다. 상속을 사용하여 기존 클래스를 기반으로 새 클래스를 만들고 추가 기능을 추가할 수 있습니다.
1class Animal {
2 constructor(name) {
3 this.name = name;
4 }
5
6 speak() {
7 console.log(`${this.name} makes a noise`);
8 }
9}
10
11// Inherit from the Animal class
12class Dog extends Animal {
13 constructor(name, breed) {
14 super(name); // Call the constructor of the parent class (Animal)
15 this.breed = breed;
16 }
17
18 // Override the method
19 speak() {
20 console.log(`${this.name} barks`);
21 }
22}
23
24const dog = new Dog("Rex", "German Shepherd");
25dog.speak(); // Rex barks
이 예제에서는 Dog
클래스가 Animal
클래스를 상속받습니다.
extends
키워드를 사용하여Animal
클래스를 상속받습니다.Dog
클래스의 생성자에서는super()
를 사용하여 부모 클래스의 생성자를 호출합니다. 이를 통해 부모 클래스의 초기화 과정을 상속받을 수 있습니다.- 상속받은 클래스 내에서는 부모 클래스의 메서드를 재정의할 수 있습니다. 이 예제에서는 "Rex makes a noise" 대신 "Rex barks"가 출력됩니다.
정적 메서드
클래스 내에 정적 메서드를 정의하면, 해당 메서드는 클래스 자체와 연결됩니다. 정적 메서드는 인스턴스화하지 않고도 호출할 수 있습니다.
1class MathUtils {
2 // Static method
3 static add(a, b) {
4 return a + b;
5 }
6}
7
8console.log(MathUtils.add(5, 10)); // 15
이 예제에서는 MathUtils
클래스에 정적 메서드 add
가 정의되어 있습니다.
static
키워드는 정적 메서드를 정의하는 데 사용됩니다.- 정적 메서드는 클래스 인스턴스에 속하지 않으며 클래스 자체에서 직접 호출할 수 있습니다.
게터와 세터
클래스에서 게터와 세터를 정의하면 속성의 가져오기와 설정을 캡슐화할 수 있습니다.
1class Rectangle {
2 constructor(width, height) {
3 this.width = width;
4 this.height = height;
5 }
6
7 // Getter
8 get area() {
9 return this.width * this.height;
10 }
11
12 // Setter
13 set widthValue(newWidth) {
14 this.width = newWidth;
15 }
16}
17
18const rect = new Rectangle(10, 20);
19console.log(rect.area); // 200
20
21rect.widthValue = 15;
22console.log(rect.area); // 300
이 예제에서는 Rectangle
클래스가 area
게터와 widthValue
세터를 정의하고 있습니다.
- 게터 (
get
)는 속성 값을 가져올 때 호출됩니다. - 세터 (
set
)는 속성 값을 설정할 때 호출됩니다.
클래스 문법 설탕
JavaScript에서 클래스 문법은 내부적으로 생성자 함수와 프로토타입을 사용하여 구현됩니다. 클래스 문법은 이를 더 간결하게 작성하기 위한 구문 설탕입니다.
1// Example without using class syntax
2function Person(name, age) {
3 this.name = name;
4 this.age = age;
5}
6
7Person.prototype.greet = function() {
8 return `Hello, my name is ${this.name}`;
9};
10
11const person = new Person("Alice", 25);
12console.log(person.greet()); // Hello, my name is Alice
이 예제에서는 생성자 함수 Person
이 정의되고, 프로토타입을 사용하여 greet
메서드가 정의됩니다.
this
처리하기
클래스 내부의 this
키워드는 해당 클래스의 인스턴스를 가리킵니다. 그러나 클래스 메서드에서 this
를 다룰 때는 스코프에 따라 동작이 달라질 수 있다는 점을 주의해야 합니다. 특히 메서드를 콜백 함수로 사용할 때 문제가 발생할 수 있습니다.
1class Counter {
2 constructor() {
3 this.count = 0;
4 }
5
6 increment() {
7 this.count++;
8 console.log(this.count);
9 }
10}
11
12const counter = new Counter();
13setTimeout(counter.increment, 1000); // NaN
14// NaN, since this.count is undefined, it becomes NaN after incrementing.
이런 경우, setTimeout
에 콜백으로 전달되면 this
의 참조 대상이 변경될 수 있습니다. 이 문제를 피하려면 bind
메서드를 사용하여 this
를 고정하거나 화살표 함수를 사용하는 것이 권장됩니다.
1class Counter {
2 constructor() {
3 this.count = 0;
4 }
5
6 increment() {
7 this.count++;
8 console.log(this.count);
9 }
10}
11
12const counter = new Counter();
13
14// When using bind
15setTimeout(counter.increment.bind(counter), 1000);
16
17// When using an arrow function
18setTimeout(() => counter.increment(), 2000);
요약
- 클래스는 객체 생성을 위한 청사진으로, 속성과 메서드를 정의하는 데 사용됩니다.
- 객체 지향 개념을 활용하여 상속을 통해 클래스를 확장할 수 있습니다.
- 정적 메서드는 클래스 자체에 속하며 인스턴스를 생성하지 않고도 사용할 수 있습니다.
- 게터와 세터를 사용하여 속성을 캡슐화할 수 있습니다.
- JavaScript의 클래스 문법은 문법적 설탕에 불과하며 내부적으로 프로토타입 기반 상속을 사용합니다.
클래스를 사용하면 객체지향 프로그래밍을 더 자연스럽게 다룰 수 있으며, 코드의 재사용성과 유지 보수를 향상시킬 수 있습니다.
위의 기사를 보면서 Visual Studio Code를 사용해 우리 유튜브 채널에서 함께 따라할 수 있습니다. 유튜브 채널도 확인해 주세요.