javascript 객체 지향 프로그래밍 (Object-Oriented Programming, OOP)

Kiyun·2024년 1월 18일

js

목록 보기
9/20

javascript 객체 지향 프로그래밍 (Object-Oriented Programming, OOP)

자바스크립트에서 객체 지향 프로그래밍(Object-Oriented Programming, OOP)은 객체를 중심으로 하는 프로그래밍 패러다임입니다. OOP는 코드를 객체로 모델링하여 프로그램을 구조화하고, 객체 간의 상호작용을 통해 기능을 구현합니다. 자바스크립트는 OOP를 지원하며, 프로토타입 기반의 객체 지향 언어입니다.

OOP의 주요 개념:

1. 클래스(Class)

객체를 생성하기 위한 템플릿 또는 설계도입니다. 클래스는 속성(프로퍼티)과 메서드를 정의하며, 이를 기반으로 객체를 생성합니다.

클래스 정의 및 인스턴스 생성:

class Person {
    // 생성자 메서드
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    // 일반 메서드
    sayHello() {
        console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
    }
}

// 클래스를 기반으로 객체(인스턴스) 생성
const person1 = new Person('John', 30);
const person2 = new Person('Jane', 25);

// 객체의 메서드 호출
person1.sayHello();  // 출력: "Hello, my name is John and I am 30 years old."
person2.sayHello();  // 출력: "Hello, my name is Jane and I am 25 years old."

상속

클래스는 상속을 통해 다른 클래스의 속성과 메서드를 가져와 확장할 수 있습니다.

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

    // 메서드 오버라이딩
    sayHello() {
        console.log(`Hello, my name is ${this.name}, I am ${this.age} years old, and my student ID is ${this.studentId}.`);
    }
}

const student = new Student('Alice', 22, 'S12345');
student.sayHello();  // 출력: "Hello, my name is Alice, I am 22 years old, and my student ID is S12345."

프라이빗 필드

ES2022부터 도입된 프라이빗 필드(private field)를 사용하여 클래스 내부에서만 접근 가능한 변수를 선언할 수 있습니다.

class Counter {
    #count = 0;  // 프라이빗 필드

    increment() {
        this.#count++;
    }

    getCount() {
        return this.#count;
    }
}

const counter = new Counter();
counter.increment();
console.log(counter.getCount());  // 출력: 1

2. 객체(Object)

클래스의 인스턴스로, 속성과 메서드를 가지고 있는 데이터 구조입니다.

console.log(myCar.make);  // 출력: "Toyota"
myCar.drive();            // 출력: "Driving..."

3. 상속(Inheritance)

부모 클래스(슈퍼 클래스)의 속성과 메서드를 자식 클래스(서브 클래스)가 상속받아 사용하는 개념입니다.

class ElectricCar extends Car {
    constructor(make, model, batteryCapacity) {
        super(make, model);
        this.batteryCapacity = batteryCapacity;
    }

    charge() {
        console.log('Charging...');
    }
}

const myElectricCar = new ElectricCar('Tesla', 'Model S', '100 kWh');

4. 다형성(Polymorphism)

동일한 인터페이스를 사용하여 다양한 형태의 객체를 다루는 개념입니다.

function displayInfo(vehicle) {
    console.log(`Make: ${vehicle.make}, Model: ${vehicle.model}`);
}

displayInfo(myCar);
displayInfo(myElectricCar);

5. 캡슐화(Encapsulation)

객체의 상태를 나타내는 속성과 그 상태를 조작하는 메서드를 하나로 묶고, 외부에서 직접 접근하지 못하도록 은닉하는 개념입니다.

class Counter {
    #count = 0;  // 프라이빗 필드

    increment() {
        this.#count++;
    }

    getCount() {
        return this.#count;
    }
}

const counter = new Counter();
counter.increment();
console.log(counter.getCount());  // 출력: 1

자바스크립트는 프로토타입 기반의 객체 지향 언어이기 때문에 명시적인 클래스 정의보다는 프로토타입과 객체 리터럴을 사용하여 객체를 생성하는 경우가 많습니다. ES6 이후에는 클래스 문법이 추가되어 명시적인 클래스 기반의 OOP도 지원됩니다.

0개의 댓글