자바스크립트의 클래스에 데이터 은닉(캡슐화)이라는 객체지향의 꽃을 피우게 해주는 접근 제어자(Modifiers)입니다.
실행해보기
아래의 코드는 Minstudio의 엔진을 통해 브라우저 상에서 타입스크립트로 변환되어 실행된 결과입니다. 하단의 Developer Console 창에서 console.log의 출력을 직접 확인해보세요!
// 클래스 선언
class Animal {
// 속성 (Property) - 최신 문법에서는 먼저 선언해주는 것이 좋습니다.
name: string;
// 생성자 (Constructor): 객체가 처음 'new'로 만들어질 때 실행되는 초기화 함수
constructor(animalName: string) {
this.name = animalName;
}
// 메서드 (Method): 클래스 안에 있는 함수
makeSound() {
console.log(`${this.name}가 소리를 냅니다.`);
}
}
// 클래스를 사용하여 객체(인스턴스) 생성
const dog = new Animal("바둑이");
dog.makeSound(); // "바둑이가 소리를 냅니다." 출력
🔒 localhost:8000/preview
class UserAccount {
public username: string; // 어디서든 접근 가능
protected email: string; // 자식 클래스까지만 접근 가능
private secretKey: string; // 오직 이 클래스 안에서만!
constructor(name: string, email: string) {
this.username = name;
this.email = email;
this.secretKey = "SUPER_SECRET";
}
// 메서드를 통해 private 값에 간접적으로 접근
checkSecret() {
console.log(`${this.username}의 비밀키: ${this.secretKey}`);
}
}
const account = new UserAccount("Minstudio", "admin@minstudio.com");
console.log("public 속성 접근:", account.username);
// console.log(account.email); // ❌ 에러: protected 속성
// console.log(account.secretKey); // ❌ 에러: private 속성
account.checkSecret(); // 정상 출력