Javascript๋ ๋ณธ์ง์ ์ผ๋ก ๊ฐ์ฒด ๊ธฐ๋ฐ ์ธ์ด์ ๋๋ค.
OOP(Object-Oriented Programming)์ ํต์ฌ์ ๋ค์ ๋ค ๊ฐ์ง์ ๋๋ค
- ์ถ์ํ (Abstraction)
- ์บก์ํ (Encapsulation)
- ์์ (Inheritance)
- ๋คํ์ฑ (Polymorphism)
1๏ธโฃ ์ถ์ํ (Abstraction)
๋ถํ์ํ ์ธ๋ถ ์ ๋ณด๋ฅผ ์จ๊ธฐ๊ณ , ์ค์ํ ๋ถ๋ถ๋ง ๋ ธ์ถํ๋ ๊ฒ
์์:
class CoffeeMachine {
constructor(brand) {
this.brand = brand;
}
makeEspresso() {
this.#boilWater();
console.log(`${this.brand} ๋จธ์ : ์์คํ๋ ์ ์์ฑ!`);
}
#boilWater() {
console.log('๋ฌผ์ ๋์ด๋ ์ค...');
}
}
const cm = new CoffeeMachine('Nespresso');
cm.makeEspresso(); // ์์คํ๋ ์ ์์ฑ!
- ๋ด๋ถ ๋์(boilWater())์ ์จ๊ฒจ์ง
- ์ฌ์ฉ์ ์ ์ฅ์์ ๋จ์ํ makeEspresso()๋ง ์๋ฉด ๋จ
2๏ธโฃ ์บก์ํ (Encapsulation)
๊ฐ์ฒด ๋ด๋ถ ์ํ๋ฅผ ์จ๊ธฐ๊ณ , ํ์ํ ์ธํฐํ์ด์ค๋ง ๊ณต๊ฐํ๋ ๊ฒ
โ ์์ (Private ํ๋):
class BankAccount {
#balance = 0;
deposit(amount) {
if (amount > 0) this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
const myAccount = new BankAccount();
myAccount.deposit(1000);
console.log(myAccount.getBalance()); // 1000
// myAccount.#balance → โ ์๋ฌ
- #balance๋ ์ธ๋ถ์์ ์ง์ ์ ๊ทผ ๋ถ๊ฐ (์บก์ํ)
3๏ธโฃ ์์ (Inheritance)
๊ธฐ์กด ํด๋์ค์ ์์ฑ๊ณผ ๋ฉ์๋๋ฅผ ์์ ํด๋์ค๊ฐ ๋ฌผ๋ ค๋ฐ๋ ๊ฒ
โ ์์:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks`);
}
}
const dog = new Dog('Buddy');
dog.speak(); // Buddy barks
- Dog๋ Animal์ ์์ฑ ๋ฐ ๋ฉ์๋๋ฅผ ์์๋ฐ๊ณ , speak()๋ ์ค๋ฒ๋ผ์ด๋ฉ
4๏ธโฃ ๋คํ์ฑ (Polymorphism)
๊ฐ์ ๋ฉ์๋๋ช ์ด ์ํฉ์ ๋ฐ๋ผ ๋ค๋ฅด๊ฒ ๋์ํ๋ ๊ฒ
โ ์์ (์ค๋ฒ๋ผ์ด๋ฉ):
const animals = [
new Dog('Max'),
new Animal('Generic')
];
animals.forEach(animal => animal.speak());
๊ฒฐ๊ณผ:
Max barks
Generic makes a sound
- speak()๋ ๊ฐ ํด๋์ค์ ๋ฐ๋ผ ๋ค๋ฅด๊ฒ ๊ตฌํ๋จ
- ํ๋์ animal.speak() ํธ์ถ์ด ์ฌ๋ฌ ํํ๋ก ๋์ → ๋คํ์ฑ
๐ท React ์ปดํฌ๋ํธ์ OOP ๊ฐ๋
React๋ ํจ์ํ ์ปดํฌ๋ํธ ๊ธฐ๋ฐ์ด์ง๋ง, OOP์ ์ฌ๊ณ ๋ฐฉ์์ ๋ค์๊ณผ ๊ฐ์ด ๊ทธ๋๋ก ์ ์ฉ๋ฉ๋๋ค.
OOP ํน์ฑ React์์์ ์
์ถ์ํ | ์ปดํฌ๋ํธ๋ก UI ๋จ์ ์ถ์ํ (<Button />) |
์บก์ํ | props/state๋ ์ธ๋ถ์์ ์ง์ ์ ๊ทผ ๋ถ๊ฐ |
์์ | HOC, ํด๋์คํ ์ปดํฌ๋ํธ์์ extends React.Component |
๋คํ์ฑ | ๋์ผํ ์ปดํฌ๋ํธ ์ด๋ฆ์ด๋ผ๋ props์ ๋ฐ๋ผ ๋ค๋ฅด๊ฒ ๋ ๋๋ง |
const Button = ({ type }) => {
return <button>{type === 'submit' ? '์ ์ถ' : '์ทจ์'}</button>;
};
- ๊ฐ์ <Button /> ์ปดํฌ๋ํธ๋ props์ ๋ฐ๋ผ ๋ค๋ฅด๊ฒ ๋์ → ๋คํ์ฑ ๊ฐ๋ ์ ์ฉ
๊ฒฐ๋ก
ํน์ฑ ์ค๋ช JS ์์ ํค์๋
์ถ์ํ | ์ค์ํ ๊ฒ๋ง ๋ณด์ด๊ฒ | private ๋ฉ์๋, interface ์ญํ |
์บก์ํ | ๋ด๋ถ ์จ๊ธฐ๊ธฐ | #ํ๋, getter/setter |
์์ | ์ฝ๋ ์ฌ์ฌ์ฉ | class A extends B |
๋คํ์ฑ | ๋์ผ ์ธํฐํ์ด์ค, ๋ค๋ฅธ ๊ตฌํ | ๋ฉ์๋ ์ค๋ฒ๋ผ์ด๋ฉ |
'Developing๐ฉโ๐ป > Front-end' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JS] ํจ์ ์์๋ก ์ดํด๋ณด๋ static ๋ฉ์๋ ํ์ฉ๋ฒ (1) | 2025.07.13 |
---|---|
[JS] JavaScript์static ์ด๋? (0) | 2025.07.13 |
[typescript] ์กฐ๊ฑด๋ณ ํ์ ์ ํ๊ธฐ (0) | 2024.03.05 |
[React] state์ ๋ณ๊ฒฝ๊ณผ lodash์ debounce๋ฅผ ๋์์ ํธ์ถํ๊ธฐ (0) | 2024.03.04 |
[๋ฒ์ญ] React19์ ๋์ ๋๋ ์๋ก์ด clien-side hook๋ค (0) | 2024.02.12 |