[JavaScript]
기초
- [JS] Js기초
- [JS] Js기초 변수
- [JS] Js기초 자료형
- [JS] Js기초 형변환
- [JS] Js기초 연산자
- [JS] Js기초 반복문
- [JS] Js기초 switch
- [JS] Js기초 function
- [JS] Js기초 객체
- [JS] Js기초 배열
중급
- [JS] Js중급 호이스팅(Hoisting)과 TDZ(Temporal Dead Zone)
- [JS] Js중급 생성자함수
- [JS] 객체 메소드(Object methods), 계산된 프로퍼티(Computed property)
- [JS] 심볼(Symbol)
- [JS] WeakMap WeakSet
- [JS] 숫자, 수학 method (Number, Math)
- [JS] 문자열 메소드(String methods)
- [JS] 배열 메소드(Array methods)
- [JS] 구조 분해 할당 (Destructuring assignment)
- [JS] 매개변수 리스트와 전개 문법(Rest parameters and spread syntax)
- [JS] 클로저(Closure)
- [JS] setTimeout / setInterval
- [JS] call / apply / bind
- [JS] 상속, 프로토타입(Prototype)
- [JS] 클래스(Class)
- [JS] 클로미스(Promise)
- [JS] 비동기 처리(Async/Await)
- [JS] Generator
- [JS] 메모리 릭(Memory Leak)
클래스(Class)! 객체 지향 프로그래밍의 핵심 문법이야! 📚
1. 클래스 기본 문법
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
| class Person {
// 생성자
constructor(name, age) {
this.name = name;
this.age = age;
}
// 인스턴스 메서드
introduce() {
console.log(`안녕하세요, ${this.name}입니다.`);
}
// 정적(static) 메서드
static createAnonymous() {
return new Person("Anonymous", 0);
}
// getter
get info() {
return `${this.name}, ${this.age}세`;
}
// setter
set age(value) {
if (value < 0) throw new Error("나이는 음수일 수 없습니다");
this._age = value;
}
get age() {
return this._age;
}
}
const person = new Person("김코딩", 20);
person.introduce(); // "안녕하세요, 김코딩입니다."
console.log(person.info); // "김코딩, 20세"
const anonymous = Person.createAnonymous();
console.log(anonymous.name); // "Anonymous"
|
2. 클래스 상속
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
| class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name}이(가) 소리를 냅니다`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // 부모 클래스 생성자 호출
this.breed = breed;
}
speak() {
super.speak(); // 부모 메서드 호출
console.log("멍멍!");
}
fetch() {
console.log(`${this.name}이(가) 공을 가져옵니다`);
}
}
const dog = new Dog("멍멍이", "진돗개");
dog.speak();
// "멍멍이이(가) 소리를 냅니다"
// "멍멍!"
|
3. 접근 제어자 (Private 필드)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
| class BankAccount {
// private 필드 (#으로 시작)
#balance = 0;
constructor(initialBalance) {
this.#balance = initialBalance;
}
deposit(amount) {
if (amount > 0) {
this.#balance += amount;
return true;
}
return false;
}
withdraw(amount) {
if (amount > 0 && this.#balance >= amount) {
this.#balance -= amount;
return true;
}
return false;
}
get balance() {
return this.#balance;
}
}
const account = new BankAccount(1000);
console.log(account.balance); // 1000
console.log(account.#balance); // SyntaxError: Private field
|
4. 믹스인과 다중 상속 흉내내기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
| // 믹스인 함수
const swimmable = {
swim() {
console.log(`${this.name}이(가) 수영합니다`);
},
};
const flyable = {
fly() {
console.log(`${this.name}이(가) 날아갑니다`);
},
};
class Duck extends Animal {
constructor(name) {
super(name);
// 믹스인 적용
Object.assign(this, swimmable, flyable);
}
}
const duck = new Duck("도널드");
duck.speak(); // "도널드이(가) 소리를 냅니다"
duck.swim(); // "도널드이(가) 수영합니다"
duck.fly(); // "도널드이(가) 날아갑니다"
|
5. 실전 예제: UI 컴포넌트
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
| class Component {
constructor(selector) {
this.element = document.querySelector(selector);
this.state = {};
this.init();
}
init() {
this.render();
this.setEventListeners();
}
setState(newState) {
this.state = { ...this.state, ...newState };
this.render();
}
render() {
// 추상 메서드
throw new Error("render 메서드를 구현해야 합니다");
}
setEventListeners() {
// 추상 메서드
}
}
class TodoList extends Component {
constructor(selector) {
super(selector);
this.state = {
todos: [],
};
}
render() {
this.element.innerHTML = `
<ul>
${this.state.todos.map((todo) => `<li>${todo}</li>`).join("")}
</ul>
`;
}
addTodo(text) {
this.setState({
todos: [...this.state.todos, text],
});
}
}
const todoList = new TodoList("#todo-list");
todoList.addTodo("JavaScript 공부하기");
todoList.addTodo("클래스 마스터하기");
|
6. 고급 패턴: 싱글톤
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| class Singleton {
static #instance;
constructor() {
if (Singleton.#instance) {
return Singleton.#instance;
}
Singleton.#instance = this;
}
static getInstance() {
if (!Singleton.#instance) {
Singleton.#instance = new Singleton();
}
return Singleton.#instance;
}
}
const instance1 = new Singleton();
const instance2 = new Singleton();
console.log(instance1 === instance2); // true
|
꿀팁! 🍯
- 클래스 필드 선언
1
2
3
4
5
6
7
8
9
10
11
| class Example {
// 클래스 필드
name = "기본값";
#privateField = "비밀";
static staticField = "정적";
// 메서드
method() {
console.log(this.name, this.#privateField);
}
}
|
- 메서드 체이닝
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| class Calculator {
constructor() {
this.value = 0;
}
add(n) {
this.value += n;
return this;
}
subtract(n) {
this.value -= n;
return this;
}
getResult() {
return this.value;
}
}
const calc = new Calculator();
console.log(
calc.add(5).subtract(2).add(3).getResult() // 6
);
|
이제 클래스는 마스터! 😎
객체 지향 프로그래밍을 자유자재로 할 수 있을 거야!