[OOP] private & static

nearworld·2022년 12월 6일
0

javascript

목록 보기
4/7
class FakeMath {
	private constructor() {}
	static divide(a: number, b: number) {
		return a / b;
	}
}

/* 
	에러[1]: 생성자가 private이면 생성자 함수 호출 불가능
	에러 메세지: Constructor of class 'FakeMath' is private and 
	only accessible within the class declaration.
*/
const fake = new FakeMath(); // 에러[1]
FakeMath.divide(1, 2); // 정상 작동
class FakeMath {
	static divide(a: number, b: number) {
		return a / b;
	}
}

const fake = new FakeMath();

/*
	에러[1]: 멤버가 static 지정이면 클래스 레벨에서만 사용 가능. 인스턴스에선 사용 불가능.
	에러 메세지: Property 'divide' does not exist on type 'FakeMath'. 
	Did you mean to access the static member 'FakeMath.divide' instead?
*/
fake.divide(1, 2); // 에러[1]
profile
깃허브: https://github.com/nearworld

0개의 댓글