ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • TS 클래스
    JavaScript/TypeScript 2021. 6. 23. 05:26

     

    클래스

     

    - 객체 (object)를 만드는 설계도

    - 클래스 이전에 object를 만드는 기본적인 방법은 Function

    - JS에도 class 사용 가능 (es6 부터)

    - OOP (Object-Oriented Programming)을 위한 초석

    - TS에서는 클래스도 사용자가 만드는 타입의 하나

     

     

    기본 형태의 클래스

     

    // class 클래스명 {}
    class Person {
      name: string;
    
      // constructor (생성자 키워드)
      // object를 생성하면서 값을 전달
      constructor(name: string) {
        // this를 이용해서 만들어진 object를 가리킨다
        this.name = name;
      }
    }
    
    // new 키워드를 이용하여 class를 통해 object를 만들 수 있다
    const p1 = new Person("Yoo");
    
    // Person { name: 'Yoo' }
    console.log(p1);

     

    생성자 (constructor) & 초기화 (initialize)

     

    - 생성자 함수가 없으면, 디폴트 생성자가 불린다 (생성자가 있으면 디폴트 생성자는 사라진다)

    - strict 모드에서는 프로퍼티를 선언하는 곳 또는 생성자에게 값을 할당해야 한다

    - 프로퍼티를 선언하는 곳 또는 생성자에게 값을 할당하지 않는 경우에는 !를 붙여 위험을 표시

    - 클래스의 프로퍼티가 정의되어 있지만, 값을 대입하지 않으면 undefined 이다

    - 생성자에는 async 를 설정할 수 없다

     

    접근 제어자 (Access Modifiers)

     

    - public, private, protected

    - 설정하지 않으면 public (어디에서나 접근할 수 있다)

    - private (클래스 내부에서만 접근할 수 있다)

    - protected (상속 관계에서는 접근할 수 있다)

    - 클래스 내부의 모든 곳에 (생성자, 프로퍼티, 메서드) 설정 가능

     

    Getters & Setters

     

    class Person {
      constructor(private _name:string, private age:number) {}
    
      get name() {
        return this._name;
      }
    
      set name(n: string) {
        this._name = n;
      }
    }
    
    const p1 = new Person("Yoo", 27);
    
    // Yoo
    console.log(p1.name); // getter
    
    p1.name = "Lee"; // setter
    
    // Lee
    console.log(p1.name)

     

    readonly properties

     

    - readonly가 선언된 클래스 프로퍼티는 선언 시 또는 생성자 함수 내부에서만 값을 할당 가능

    - 읽기만 가능하고 재할당 불가능

     

    Index Signatures in class

     

    // [key: type]: valueType
    class Students {
      //[index: string]: string;
      [index: string]: "male" | "female";
    }
    
    const a = new Students();
    a.Kim = "male";
    a.Lee = "female";
    
    // Students { Kim: 'male', Lee: 'false' }
    console.log(a);
    
    const b = new Students();
    b.Park = "female";
    b.Lee = "male";
    b.Yoo = "male";
    
    // Students { Park: 'female', Lee: 'male', Yoo: 'male' }
    console.log(b);

     

    Static Properties & Method

     

    - TS에서는 static 키워드를 클래스 프로퍼티와 클래스 메서드에 사용할 수 있다

    - 인스턴스가 아닌 클래스 이름으로 호출

     

    class Person {
      private static NAME = "Kim";
    
      public static hello() {
        console.log(`TS Hello! 내 이름은 ${this.NAME}`);
      }
    }
    
    const p1 = new Person();
    
    // p1.hello(); (에러 발생)
    
    // TS Hello! 내 이름은 Kim
    Person.hello();
    

     

    싱글톤 (Singletons)

     

    - GOF (Gang Of Four)에서 제안된 디자인 패턴 중 하나

    - 클래스가 오직 하나의 인스턴스만 생성

     

    class Student {
      private static instance: Student | null = null;
      public static getInstance(): Student {
        // Student 로부터 만든 object가 없으면, 만든다
        if (Student.instance === null) {
          Student.instance = new Student();
        }
    
        return Student.instance;
      }
    
      private constructor() {}
    }
    
    const a = Student.getInstance();
    const b = Student.getInstance();
    
    // true
    console.log(a === b);

     

    상속 (Inheritance)

     

    - 클래스 상속에 extends 키워드를 사용

    - super()를 사용해서 부모 클래스의 생성자를 호출

     

    class Parent {
      constructor(protected _name: string, private _age: number) {
    
      }
      public print(): void {
        console.log(`이름은 ${this._name} 나이는 ${this._age}`);
      }
    }
    
    // const p = new Parent('LEE', 45);
    // p.print();
    
    class Child extends Parent {
      constructor(_name: string, _age: number) {
        super(_name, _age);
      }
    }
    
    const c = new Child('Lee Jr', 7);
    c.print();

     

    추상 클래스 (Abstract Classes)

     

    - 추상 메서드는 정의만 하고 몸체는 구현하지 않는다

    - 추상 클래스를 상속하는 클래스를 통해 추상 메서드를 구현

    - 추상 클래스는 추상 클래스의 인스턴스를 만들 수 없다

    - 추상 클래스를 상속하는 클래스를 통해 인스턴스 생성

     

    abstract class AbstractPerson {
      protected _name: string = "Lee";
    
      abstract setName(name: string): void;
    }
    
    // new AbstractPerson(); (에러 발생)
    
    class Person extends AbstractPerson {
      setName(name: string): void {
        this._name = name;
      }
    }
    
    const p = new Person();
    p.setName('Kim');
    
    // Person { _name: 'Kim' }
    console.log(p);

    'JavaScript > TypeScript' 카테고리의 다른 글

    TS Generics  (0) 2021.06.23
    TS 인터페이스  (0) 2021.06.19
    TS 컴파일러  (0) 2021.06.18
    TS 타입 시스템  (0) 2021.06.17
    TS 타입  (0) 2021.06.12

    댓글

Designed by Tistory.