객체 지향 프로그래밍
하나의 모델이 되는 청사진을 만들고 -> class 그 청사진을 바탕으로 한 객체를 만드는 -> instance 프로그래밍 패턴
쉽게 말해 class는 상자를 만들고 instance는 상자의 색깔을 입힌다고 생각하면 된다
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//class
class Box {
constructor(color, size) {
//생성자 함수 - class가 호출될때 맨 처음 실행
this.color = color;
this.size = size;
}
checkSize() {}
}
//instance
let blue_10 = new Box("blue", 10);
console.log(blue_10.color, blue_10.size); //blue 10
//Box 내부의 checkSize 함수를 정의함
Box.prototype.checkSize = function () {
console.log(this.size);
};
console.log(blue_10.checkSize()); //10
간단한 예제
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Counter {
constructor() {
this.value = 0; // 생성자 호출을 할 경우, this는 new 키워드로 생성한 Counter의 인스턴스입니다
}
increase() {
this.value++;
}
decrease() {
this.value--;
}
getValue() {
return this.value;
}
}
let counter1 = new Counter(); // 생성자 호출
counter1.increase();
counter1.getValue(); // 1