Static Methods and Properties

kukudas·2022년 2월 8일
0

TypeScript

목록 보기
22/39

Static properties

인스턴스 property와는 다르게 static property는 클래스의 모든 인스턴스들 사이에서 공유됨.
static propoerty를 선언하기 위해서는 static키워드를 사용해야하며 static property에 접근하기 위해서는 className.propertyName 구문을 이용하면됨.

class Employee {
    static headcount: number = 0;

    constructor(
        private firstName: string,
        private lastName: string,
        private jobTitle: string) {

        Employee.headcount++;
    }
}

위 예시에서, headcountstatic property이며 0으로 초기화되어 있으며 인스턴스가 생성될 때마다 1씩 증가함.
아래는 2개의 Employee 객체를 생성하고 headcount property의 값을 살펴본건데 예상대로 2가 나옴을 알 수 있음.

let john = new Employee('John', 'Doe', 'Front-end Developer');
let jane = new Employee('Jane', 'Doe', 'Back-end Developer');

console.log(Employee.headcount); // 2

Static methods

static propoerty와 비슷하게 static method도 클래스의 인스턴스들 간에 공유됨. static method를 선언하기 위해서는 메소드 이름앞에다가 static 키워드를 붙여주면됨.

class Employee {
    private static headcount: number = 0;

    constructor(
        private firstName: string,
        private lastName: string,
        private jobTitle: string) {

        Employee.headcount++;
    }

    public static getHeadcount() {
        return Employee.headcount;
    }
}
  • 먼저, headcount static propertypublic에서 private으로 변경해 이 값이 Employee 객체를 생성하는 것 외에는 변할수 없게 만듬
  • 다음으로 getHeadCount() static method를 추가해서 headcount property를 리턴하게 했음.

static method를 부르려면 className.staticMethod()로 하면됨.

let john = new Employee('John', 'Doe', 'Front-end Developer');
let jane = new Employee('Jane', 'Doe', 'Back-end Developer');

console.log(Employee.getHeadcount()); // 2

Math 오브젝트의 PI같은 property나 abs(), round() 같은게 전부 static임.

  • static propertystatic method들은 클래스의 모든 인스턴스들이 공유함.
  • static 키워드를 붙여서 property와 method를 static하게 만들 수 있음

출처

0개의 댓글

관련 채용 정보