[TypeScript] 클래스

hello__0·2022년 8월 5일
0

class

  • class로 무조건 생성해야 한다.
  • 필드 = 속성이 들어간다.
class Person {
// 필드
  name: string;
  age: number;
  readonly location: string = "Korea";

readonly

수정이 안되도록 하고 싶을 때


생성자

  • 초기화를 담당한다.
  • class가 인스턴스화 될 때 초기화를 통해 필드들을 수정하고 초기화 할 수 있는 역할
  constructor(name: string, age: number) {
      this.name = name;
      this.age = age;
  }

여기서의 this는 생성 될 인스턴스를 바라본다.


인스턴스

  • 함수명 앞에 new를 붙여주어야 한다.
  • 클래스에서 파생된 고유한 것이다.
  • 생성된 후에 메모리에 올라간다.
const student1 = new Person('Jeong', 56);
const student2 = new Person('Choi', 28);

person이라는 함수를 거친 class가 인스턴스화가 된다.
student1, student2가 인스턴스이다.


결론

class 안에는 필드와 생성자가 존재한다.
그리고 인스턴스를 통해 class에 쉽게 접근 할 수 있고,
생성자를 통해 초기화가 가능하다.
생성자의 this는 인스턴스를 가르킨다.

// 클래스
class Person {
	// 필드
    name: string;
    age: number;
    readonly location: string = "Korea";
  
    // 생성자
    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    };
  };
  
// 인스턴스
const student1 = new Person('Jeong', 56);
const student2 = new Person('Choi', 28);

profile
자라나라 나무나무

0개의 댓글