ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • TypeScript[5] Class
    Language/TypeScript 2018. 7. 30. 18:10




    - Class



    기존의 JavaScript는 재사용 가능한 component를 만들기 위해 함수와 프로토타입에 기반한 상속을 이용했다.

    하지만 C#, Java 와 같이 객체 지향에 익숙한 개발자들에겐 어려운 개념들이었다.

    그래서 ECMAScript2015(ES6)에서 개발자들이 좀더 쉽게 JavaScript Application을 구현할수 있도록 전통적인 class 기반의 객체지향 개념을 도입했다.


    class Book {
    btitle : string; // property 선언
    bauthor : string;

    constructor(btitle : string,bauthor : string){ // constructor 선언
    this.btitle=btitle;
    this.bauthor=bauthor;
    }

    printInfo() : void{ //함수 선언
    console.log(`제목 : ${this.btitle}, 저자 : ${this.bauthor}`)
    }
    }

    let book = new Book('젊은 베르테르의 슬픔','괴테'); // 클래스 할당

    book.printInfo(); // 제목 : 젊은 베르테르의 슬픔 , 저자 : 괴테



    -static 



    ES6(ECMAScript2015)에서 클래스에 static 키워드를 제공한다.

    하지만 ES6의 static은 메소드 전용으로, 프로퍼티에는 활용할수 없는 키워드이다.

    다행이도 TypeScirpt 에서는 static 키워드를 프로퍼티에도 활용 할수 있다.


    class Rect {
    width : number;
    height : number;
    static count : number=0;

    constructor(width : number, height : number){
    this.width=width;
    this.height=height;
    Rect.count++;
    }
    }
    new Rect(10,10);
    new Rect(10,20);

    console.log(Rect.count);



    - Access modifier



    JavaScript 는 프로토 타입 기반의 스크립트 언어이기 때문에 접근 제한자에 대한 기능을 지원하지 않는다. ES6에서도 마찬가지,

    private 에 해당하는 변수 앞에 언더스코어( _ )를 넣어줌으로써 이 변수가 private으로 사용된다는 컨밴션을 사용하곤 하지만, 외부에서 접근을 막을 수는 없다. 

    하지만 TypeScript는 접근 제한자 private,public,protected 같은 키워드를 지원해준다.


    class Rect {
    private width : number;
    private height : number;
    static count : number=0;

    constructor(width : number, height : number){
    this.width=width;
    this.height=height;
    Rect.count++;
    }
    }
    const rect = new Rect(10,10);

      rect.width  // error width 프로퍼티는 private 으로 선언되어 있어 오직 Rect class 안에서 정의가능




    - Readonly 제한자



    TypeScript에는 이외에도 readonly라는 특별한 제한자를 하나 제공한다. 이름에서 쉽게 유추할수 있듯이 읽기만 가능한 프로퍼티를 선언할때 사용된다.

    쉽게 말해 프로퍼티를 위해 사용할 수 있는 const 인 것이다.


    readonly는 접근 제한자와 섞어서도 사용할 수 있다. 


    class Rect {
    private readonly width : number;
    private readonly height : number;

    constructor(width : number ,height : number){
    this.width = width;
    this.height= height;
    }

    set widthMethod(width : number){
    this.width= width; // error Cannot assign to 'width' because it is a constant or a read-only property.
    }
    }


    https://moon9342.github.io/typescript-class


    https://hyunseob.github.io/2016/10/17/typescript-class/


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

    TypeScript[6] Function  (0) 2018.08.04
    TypeScript[4] Interface  (0) 2018.07.30
    TypeScript[3] - 변수 선언  (0) 2018.07.23
    TypeScript[2] - 기본 타입  (0) 2018.02.16
    TypeScript[1] - 설치,tsconfig.json  (0) 2018.02.16
Designed by Tistory.