JAVASCRIPT

javascript class

funfunweb 2024. 10. 23. 13:51

자바스크립트에서 클래스를 만드는 방법은 다음과 같습니다. 기본적인 구조와 요소를 설명할게요.

1. 클래스 정의

클래스를 정의할 때 class 키워드를 사용합니다.

 

class ClassName {
    // 생성자
    constructor(parameters) {
        // 초기화 코드
    }

    // 메서드
    methodName() {
        // 메서드 코드
    }
}

 

 

2. 생성자

생성자는 클래스의 인스턴스가 생성될 때 호출되는 특수한 메서드입니다. 객체의 초기 상태를 설정하는 데 사용됩니다.

3. 메서드

클래스 내에 정의된 함수입니다. 객체가 수행할 수 있는 동작을 정의합니다.

예제

아래는 학생 객체를 표현하는 Student 클래스를 만드는 예제입니다.

 

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

    // 학생 정보 출력 메서드
    displayInfo() {
        console.log(`Name: ${this.name}, Age: ${this.age}, Major: ${this.major}`);
    }
}

// Student 클래스를 사용하여 객체 생성
const student1 = new Student('Alice', 20, 'Computer Science');
const student2 = new Student('Bob', 22, 'Mathematics');

student1.displayInfo(); // "Name: Alice, Age: 20, Major: Computer Science"
student2.displayInfo(); // "Name: Bob, Age: 22, Major: Mathematics"

 

클래스 상속

클래스는 다른 클래스를 상속받아 확장할 수 있습니다. 이를 통해 코드의 재사용성을 높일 수 있습니다.

class GraduateStudent extends Student {
    constructor(name, age, major, thesisTitle) {
        super(name, age, major); // 부모 클래스의 생성자 호출
        this.thesisTitle = thesisTitle;
    }

    displayThesis() {
        console.log(`${this.name}'s thesis title is "${this.thesisTitle}".`);
    }
}

const gradStudent = new GraduateStudent('Charlie', 25, 'Physics', 'Quantum Mechanics');
gradStudent.displayInfo(); // "Name: Charlie, Age: 25, Major: Physics"
gradStudent.displayThesis(); // "Charlie's thesis title is "Quantum Mechanics"."

 

위 예제에서는 Student 클래스를 상속받아 GraduateStudent 클래스를 만들었습니다. 이 클래스는 부모 클래스의 속성을 유지하면서도 새로운 속성과 메서드를 추가할 수 있습니다.

 

 

자바스크립트에서 클래스는 객체 지향 프로그래밍을 위한 구조로, 객체의 템플릿 역할을 합니다. 클래스는 생성자, 메서드, 상속 등을 정의할 수 있습니다.

예를 들어:

 

 

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

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

class Dog extends Animal {
    speak() {
        console.log(`${this.name} barks.`);
    }
}

const dog = new Dog('Buddy');
dog.speak(); // "Buddy barks."

 

 

이 예제에서 Animal 클래스를 기반으로 Dog 클래스가 상속받아 더 구체적인 메서드를 정의합니다.

 

객체의 템플릿 역할은 특정한 형태와 동작을 가진 객체를 생성할 수 있는 청사진을 제공하는 것입니다. 클래스는 이러한 템플릿을 정의하고, 이를 통해 여러 개의 객체를 쉽게 생성할 수 있습니다.

 

예를 들어, 자동차를 나타내는 클래스를 만들어보겠습니다.

 

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

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

// Car 클래스를 사용하여 여러 자동차 객체 생성
const car1 = new Car('Toyota', 'Camry', 2021);
const car2 = new Car('Honda', 'Accord', 2022);

car1.displayInfo(); // "2021 Toyota Camry"
car2.displayInfo(); // "2022 Honda Accord"

 

위 예제에서 Car 클래스는 자동차의 브랜드, 모델, 연도를 속성으로 가지며, displayInfo 메서드를 통해 자동차 정보를 출력합니다. 이 클래스를 사용하여 car1과 car2라는 두 개의 객체를 생성했습니다. 각 객체는 서로 다른 속성 값을 가지면서도 동일한 메서드를 사용할 수 있습니다.

 

이처럼 클래스를 사용하면 코드의 재사용성과 가독성을 높일 수 있습니다.

'JAVASCRIPT' 카테고리의 다른 글

이벤트 객체  (0) 2024.10.30
객체란?  (0) 2024.10.24
javascript scope  (0) 2024.10.23
javascript strict mode 와 sloppy mode 차이점  (0) 2024.10.18
가변인자, arguments 객체란?  (0) 2024.10.18