타입스크립트 public 접근 제한자 예제
타입스크립트( Typescript )의 public은 클래스의 속성이나 메서드에 적용하는 접근 제한자로, 클래스 내부, 외부에서 해당 멤버와 메서드에 접근할 수 있도록 한다.
클래스 멤버는 별도의 접근 제한자를 작성하지 않으면 기본적으로 public으로 설정된다.
접근제한자를 명시적으로 작성하면, 해당 멤버와 메서드는 외부 접근을 명시하고 접근을 제한한다.
public은 private, protected와 함께 클래스 멤버의 접근 범위를 구분하는 데 사용되며, 타입스크립트의 클래스 구조와 객체 사용 범위를 명확하게 표현한다.
⊙
class User {
public name: string = "철수";
printName() {
console.log(this.name); // 클래스 내부 접근
}
}
const user = new User();
console.log(user.name); // 클래스 외부 접근⊙
class Calculator {
public add(a: number, b: number): number {
return a + b;
}
}
const calculator = new Calculator();
console.log(calculator.add(10, 20));⊙
/* public을 명시한 경우 */
class User {
public name: string = "철수";
public hello(): void {
console.log("안녕하세요.");
}
}⊙
/* public을 생략한 경우 */
class User {
name: string = "철수";
hello(): void {
console.log("안녕하세요.");
}
}⊙
class Product {
name: string = "키보드";
price: number = 50000;
}
const product = new Product();
console.log(product.name);
console.log(product.price);⊙
class Account {
public username: string;
private password: string;
constructor(username: string, password: string) {
this.username = username;
this.password = password;
}
}
댓글
댓글 쓰기