[제로베이스] Class를 활용해서 모듈화

eunseok·2023년 4월 29일
0
post-thumbnail

정확한 개념을 알고 넘어가기 위해 class부터 알아보겠다.

Class란?

Class는 객체를 생성하기 위한 템플릿입니다. 클래스는 데이터와 이를 조작하는 코드를 하나로 추상화합니다. 자바스크립트에서 클래스는 프로토타입을 이용해서 만들어졌지만 ES5의 클래스 의미와는 다른 문법과 의미를 가집니다.

Class 정의
Class는 사실 "특별한 함수"입니다. 함수를 함수 표현식과 함수 선언으로 정의할 수 있듯이 class 문법도 class 표현식 and class 선언 두 가지 방법을 제공합니다.
-mdn-

자동차라는 클래스 선언

class Car {
    constructor(color, brand) {
        this.color = color;
        this.brand = brand;
    }

    drive() {
        console.log(`${this.brand} ${this.color} car is driving.`);
    }
}

위의 예제에서 Car라는 클래스는 color와 brand라는 속성과 drive라는 메소드를 가지고 있습니다. 이 클래스를 사용하여 실제 자동차 객체를 생성하고 메소드를 호출할 수 있다.

const myCar = new Car("red", "Toyota");
myCar.drive(); // Toyota red car is driving.

Class를 모듈화하여 사용하는 방법

앞서 만든 Car class를 모듈화하여 다른 파일에서 이 모듈을 불러와 Car class를 사용할 수 있다!

//car.js
class Car {
    constructor(color, brand) {
        this.color = color;
        this.brand = brand;
    }

    drive() {
        console.log(`${this.brand} ${this.color} car is driving.`);
    }
}

export default Car; //Class를 모듈화하여 다른 파일에서 사용 가능하게 함.

다른 파일에서 import 구문을 사용하여 Car 클래스를 불러와 사용할 수 있다.

//myCar.js
import Car from './car.js';

const myCar = new Car("red", "Toyota");
myCar.drive(); // Toyota red car is driving.

--

클래스를 사용하여 각각의 기능을 구현하고 이를 조합하는 것은 객체 지향 프로그래밍의 핵심 개념 중 하나이다. 각 클래스는 하나의 책임을 가지고 이를 구현하며, 다른 클래스와 협력하여 더 큰 기능을 구현할 수 있다.

0개의 댓글