TypeScript

[TypeScript] 타입스크립트 클래스(class) 정리

이경욱 2023. 12. 19. 09:24

객체는 클래스를 기반으로 생성되며

instance라고도 불린다.

 

class Person {
	name: string;
    age: number;
	
    constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
    }
    
    sayHello() {
    console.log(`안녕하세요! 제 이름은 ${this.name}이고, 나이는 ${this.age}살 입니다.`)
    }
}

const person = new Person('Spartan', 30);
person.sayHello();

 

(1) 생성자 (constructor)

생성자는 클래스의 인스턴스를 생성하고 초기화하는데 사용되는 메서드.

클래스 내에서 오직 하나만 존재할 수 있다.

 

 

(2) 접근 제한자

a. public

클래스 외부에서도 접근이 가능하다.

선언이 안되어 있다면 default 값은 public이다.

 

b. private

클래스 내부에서만 접근이 가능하다.

 

c. protected

클래스 내부와 해당 클래스를

상속받은 자식 클래스에서만 접근 가능하다.

 

 

 

'TypeScript' 카테고리의 다른 글

[TypeScript] 객체지향 설계원칙 SOLID  (0) 2023.12.21
[TypeScript] 개요  (0) 2023.12.19