[typescript] static method

Hyo Kyun Lee·2021년 9월 16일
0

typescript

목록 보기
5/5

1. static method

class를 통한 별도의 인스턴스나 객체를 생성하지 않고도, 바로 class 내부의 함수 및 인자를 사용할 수 있는 방법

Object_from_class = new Class

위 코드처럼 Class를 통한 객체를 생성하거나, 내부 인자에 접근하기 위해선 반드시 class를 생성한 이후에 진행이 가능하였다.

그러나 static을 사용한다면 별도의 생성없이도 바로 class method를 사용할 수 있다.

2. 코드 예시

class Block {
    public index: number;
    public hash: string;
    public previousHash: string;
    public data: string;
    public timestamp: number;

    static calculateBlockhash = (index:number, previousHash:string, timestamp:number, data:string) => {
        CryptoJS.SHA256(index + previousHash + timestamp + data).toString()
    }

위 코드처럼 class 내부에 static 속성으로 함수 및 변수를 설정해준다.

//static method
Block.calculateBlockhash

그 이후 class에 바로 접근하여 해당 함수를 사용할 수 있다.

0개의 댓글