{
type CoffeeCup = {
shots: number;
hasMilk: boolean;
};
class CoffeeMaker {
*// 멤버변수*
static BEANS_GRANS_PER_SHOT = 7; *// class level*
coffeeBeans: number = 0; *// instance (object) level*
*// 생성자*
constructor(coffeeBeans: number) {
this.coffeeBeans = coffeeBeans;
}
*// 멤버함수(메소드)*
static makeMachine(coffeeBeans: number) { *// class level*
return new CoffeeMaker(coffeeBeans);
}
*// 멤버함수(메소드)*
makeCoffee(shots: number): CoffeeCup { *// instance (object) level)*
if (this.coffeeBeans < shots * CoffeeMaker.BEANS_GRANS_PER_SHOT) {
throw new Error('Not enough coffee beans!');
}
this.coffeeBeans -= shots * CoffeeMaker.BEANS_GRANS_PER_SHOT;
return {
shots: shots,
hasMilk: false,
}
}
}
*// instance level 호출 방법*
const maker = new CoffeeMaker(34);
console.log(maker);
const maker2 = new CoffeeMaker(14);
console.log(maker2);
*// class level 호출 방법*
const maker3 = CoffeeMaker.makeMachine(20);
console.log(maker3);
}
[ 클래스 - class ]
클래스 안에 정의된 변수를 멤버변수라 하고,
클래스 안에 정의된 함수를 멤버함수, 즉 메소드라 한다.
함수(메소드, 생성자) 안에 정의된 변수를 지역변수라 한다.
특징
class 내부 멤버변수 및 멤버함수(메소드)는 앞에 let, const, function을 붙이지 않는다.
멤버변수 및 멤버함수(메소드)는 class-level 과 object-level 로 나뉜다.
※ class-level (정적)
class-level 은 class 자체에 할당된 멤버변수를 의미하며, 멤버변수 앞에 static 을 붙여주며, 호출 시 Math.floor 처럼 class 이름을 붙여서 멤버변수를 호출한다.(멤버함수도 동일)
※ object-level (동적)
object-level 은 object 처럼 new 로 할당된(인스턴스화) 멤버변수를 의미하며, 호출 시 Math ma = new Math() 처럼 ma 라는 object 이름을 붙여서 멤버변수를 호출한다. (멤버함수도 동일)
메모리 관계
class-level 은 클래스 자체의 고유의 멤버변수 및 함수(메소드)를 가지기 때문에 클래스 객체를 선언 할 때마다 값이 새로운 메모리에 할당되지 않아 메모리 관리에 용이하다.
반면에, object-level 은 선언된 클래스의 객체를 통해 멤버변수 및 함수를 호출하기 때문에 클래스 객체를 선언 할 때마다 값이 새로운 메모리에 할당되어 메모리 관리에 신경을 써야한다.
사용
object 마다 새로 만들어져야 하는 데이터가 있다면 멤버변수(object-level)로 만들면 되고,
class 레벨에서 함께 공유될 수 있는 거라면 static(class-level) 을 이용하면 된다.