인스턴스 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++;
}
}
위 예시에서, headcount
는 static 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 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 property
를 public
에서 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 property
와static method
들은 클래스의 모든 인스턴스들이 공유함.static
키워드를 붙여서 property와 method를static
하게 만들 수 있음