JavaScript에서 객체지향 프로그래밍 이해하기
Source: Dev.to
Hello readers 👋, welcome back to the 9th blog in this JavaScript series.
Imagine you are a car manufacturer. You don’t build each car from scratch, right? You have a blueprint (or design) that defines what a car should have: wheels, engine, doors, colour options, etc. Then you use that blueprint to create many cars – each car is an object made from the same blueprint.
This is exactly what Object‑Oriented Programming (OOP) is all about. You create a blueprint (called a class) and then create multiple objects (called instances) from it.
In this post we’ll explore how JavaScript implements OOP using classes and objects, with simple, practical examples.
Object‑Oriented Programming (OOP)
OOP는 객체를 중심으로 코드를 구성하는 프로그래밍 스타일이다. 객체는 다음을 포함할 수 있다:
- 데이터 – 속성(예:
name,age) - 동작 – 메서드(예:
drive(),displayInfo())
핵심 아이디어는 현실 세계의 사물—사람, 자동차, 학생 등—을 코드 내 객체로 모델링하는 것이다.
현실 세계 비유: 설계도 → 객체
| Concept | 현실 세계 | 프로그래밍 |
|---|---|---|
| Blueprint (Class) | 자동차 설계도 | class Car { … } |
| Object (Instance) | 실제 자동차 (빨간색, 엔진 XYZ) | const myCar = new Car('Toyota', 'red'); |
| Multiple objects | 같은 설계도로 만든 여러 대의 자동차 | 같은 클래스에서 만든 여러 인스턴스 |
JavaScript에서 클래스란?
클래스는 객체를 만들기 위한 템플릿입니다. 클래스는 객체가 가질 데이터와 동작을 캡슐화합니다.
JavaScript는 기존 프로토타입 기반 상속 위에 문법적 설탕(syntactic sugar)으로서 ES6(2015)에서 class 문법을 도입했습니다. 클래스를 단순히 설계도(blueprint)라고 생각하면 됩니다.
구문
class ClassName {
// properties and methods
}간단한 클래스와 객체 만들기
class Car {
// Constructor – runs when a new object is created
constructor(brand, color) {
this.brand = brand;
this.color = color;
}
// Method
displayInfo() {
console.log(`This is a ${this.color} ${this.brand}.`);
}
}
// Creating objects (instances) from the class
const car1 = new Car('Toyota', 'red');
const car2 = new Car('Honda', 'blue');
car1.displayInfo(); // This is a red Toyota.
car2.displayInfo(); // This is a blue Honda.설명
constructor는 객체의 속성(this.brand,this.color)을 초기화하는 특수 메서드입니다.this는 현재 인스턴스를 가리킵니다.new Car(...)는 클래스를 기반으로 새로운 객체를 생성합니다.
생성자 메서드
constructor는 공장의 조립 라인과 같습니다: 원자재(매개변수)를 받아 객체를 생성합니다.
class Person {
constructor(name, age, city) {
this.name = name;
this.age = age;
this.city = city;
}
introduce() {
console.log(`Hi, I'm ${this.name}, ${this.age} years old, from ${this.city}.`);
}
}
const person1 = new Person('Raj', 25, 'Delhi');
person1.introduce(); // Hi, I'm Raj, 25 years old, from Delhi.생성자를 정의하지 않으면, JavaScript가 기본적으로 빈 생성자를 제공합니다.
클래스 내부 메서드
메서드는 클래스에 속하는 함수이며 객체의 동작을 정의합니다.
class Calculator {
constructor(value = 0) {
this.value = value;
}
add(num) {
this.value += num;
return this; // enables chaining
}
subtract(num) {
this.value -= num;
return this;
}
getValue() {
return this.value;
}
}
const calc = new Calculator(10);
calc.add(5).subtract(3); // chaining
console.log(calc.getValue()); // 12메서드는 this를 통해 객체의 속성을 읽고 수정할 수 있습니다.
Source:
캡슐화의 기본 아이디어
캡슐화는 데이터(속성)와 그 데이터를 조작하는 메서드를 하나의 단위(클래스)로 묶고, 내부에 대한 접근을 제어합니다.
자동차를 생각해 보세요: 엔진이 어떻게 작동하는지 알 필요 없이 운전할 수 있습니다; 스티어링 휠과 페달만 사용하면 됩니다.
JavaScript에서는 일부 속성을 “프라이빗”(진정한 프라이버시는 # 문법 사용)이라고 표시할 수 있습니다. 진정한 프라이버시가 없더라도 캡슐화는 코드를 체계적으로 유지하고 실수로 인한 간섭을 방지하는 데 도움이 됩니다.
class BankAccount {
constructor(owner, balance) {
this.owner = owner;
this.balance = balance; // 이상적으로는 이것을 프라이빗으로 만들고 싶음
}
deposit(amount) {
if (amount > 0) {
this.balance += amount;
console.log(`Deposited ${amount}. New balance: ${this.balance}`);
}
}
withdraw(amount) {
if (amount <= this.balance) {
this.balance -= amount;
console.log(`Withdrew ${amount}. New balance: ${this.balance}`);
} else {
console.log('Insufficient funds!');
}
}
}
const myAccount = new BankAccount('Satya', 1000);
myAccount.deposit(500); // Deposited 500. New balance: 1500
myAccount.withdraw(2000); // Insufficient funds!balance 속성은 여전히 공개되어 있어 이상적이지 않습니다. 최신 JavaScript에서는 #balance와 같이 선언하여 진정한 프라이빗으로 만들 수 있습니다.
결론
- OOP는 데이터와 행동을 모두 포함하는 객체를 중심으로 코드를 조직합니다.
- 클래스는 이러한 객체를 만들기 위한 청사진입니다.
- 생성자는 객체가 생성될 때 그 속성을 초기화합니다.
- 메서드는 객체가 할 수 있는 일을 정의하며,
this를 통해 객체 자체의 상태에 접근하거나 수정할 수 있습니다. - 캡슐화는 관련된 데이터와 행동을 함께 묶고, 해당 데이터에 접근하는 방식을 제어합니다.
이러한 기본 개념을 이해하면 깔끔하고 재사용 가능하며 유지 보수가 쉬운 JavaScript 코드를 작성하기가 더 쉬워집니다. 즐거운 코딩 되세요!
주요 요점
- 객체가 할 수 있는 일을 정의합니다.
- 캡슐화는 데이터와 메서드를 묶어 내부 세부 사항을 숨깁니다.
- 클래스는 동일한 구조를 가진 여러 객체를 쉽게 만들 수 있게 하여 재사용성과 조직화를 촉진합니다.
진행하면서 상속, 다형성, 프라이빗 필드와 같은 고급 OOP 개념을 배우게 될 것입니다. 지금은 클래스와 객체를 만드는 연습을 하세요 – 이것이 현대 JavaScript 개발의 기반입니다.
이 블로그가 마음에 들었길 바랍니다. 오류나 개선할 점이 있으면 알려 주세요. LinkedIn과 X에서 저를 찾을 수 있습니다; 거기서 더 많은 글을 올립니다.