클래스 메서드

omnigi·2022년 2월 13일
1

Typescript Do it

목록 보기
11/23

function함수와 this키워드

타입스크립트의 function 키워드로 만든 함수는 Function이란 클래스의 인스턴스, 즉 함수는 객체라고 했습니다.
타입스크립트에서는 function 키워드로 만든 함수에 this키워드를 사용할 수 있습니다.
하지만 화살표함수에는 this키워드를 사용할 수 없습니다.

메서드란?

method는 function으로 만든 함수 표현식을 담고 있는 속성입니다.

/* 다음 코드는 다음 오류를 발생합니다.
error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.
원인은 아래 링크에서의 의미처럼 function 으로 만든 함수는 자체 this를 가지고 있고, 
클래스 A의 method는 클래스 A의 this가 있게되어, 
결국 2개의 this(즉 function의 inner this, 클래스 A의 outer this)가 있게 되어
발생한 오류입니다. 그리고 해결 방법은 자체 this가 없는 화살표 함수 방식으로 method를 구현하는 것 입니다.
*/

export class A {
  value: number = 1
  //method: () => void = function(): void {
  method: () => void = () => {
    console.log(`value: ${this.value}`)
  }
}

클래스 메서드 구문

앞에서 작성한 코드는 구현하기도 번거롭고 가독성도 떨어집니다. 타입스크립트는 클래스에서 함수표현식을 담는 속성은 function키워드를 생략할 수 있게 하는 단축 구문을 제공합니다.

export class B {
    constructor(public value: string = "김도윤"){}
    method():void {
        console.log(`value: ${this.value}`)
    }//이부분이 
}

index.ts

import {B} from "./04/B"

let b: B = new B("박은식")
b.method()
let a: B = new B()
a.method()
//value: 박은식
//value: 김도윤

정적 메서드

클래스의 속성은 static을 속성 앞에 붙여서 정적으로 만들 수 있습니다. 메서드 또한 속성이므로 이름앞에 static을 붙여 정적 메서드를 만들 수 있습니다.

'클래스 이름.정적메서드()'형태로 호출합니다.

export class C {
    static whoAreYou():string{
      return(`I'm doyoon's class C`)
    }
  }
  
  export class D {
    static whoAreYou():string{
      return(`I'm doyoon's class D`)
    }
  }
  
  console.log(C.whoAreYou())
  console.log(D.whoAreYou())

메서드 체인

객체의 메서드를 이어서 계속 호출하는 방식의 코드를 메서드 체인(method chain) 이라고 합니다

export class Calculator {
    constructor(public value: number = 0){} //기본값 0
    add(value: number){ //function키워드 생략
        this.value +=value
        return(this)
    }
    multiply(value: number){
        this.value *=value
        return(this)
    }
}

index.ts

import {Calculator} from "./04/method-chain"

let calc = new Calculator
let result = calc.add(1).add(2).multiply(3).multiply(4).value
console.log(result)

0개의 댓글