what is static members in class?
static members 용도
static 변수들은 클래스의 instance가 아니라 클래스에 속하게 된다.
따라서 인스턴스 생성과 관련이 없고, 클래스 이름으로 접근해야 한다.
static 멤버들은 클래스의 모든 인스턴스 사이에서 공유된다.
코드 예시
class Person {
firstName: string;
lastName: string;
age: number;
constructor(firstName: string, lastName: string, age: number) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public getFirstName(): string {
return this.firstName;
}
// 생성되는 persons의 수를 트래킹하기 위해서 사용되는 static 멤버
static numberOfPersons: number = 0;
static createPerson(
firstName: string,
lastName: string,
age: number
): Person {
const person = new Person(firstName, lastName, age);
Person.numberOfPersons++;
return person;
}
}
// Person 클래스의 인스턴스 생성
const person1 = new Person("John", "Doe", 30);
const person2 = new Person("Jane", "Smith", 25);
// non static 멤버에 접근하기
console.log(person1.getFirstName()); // John Doe
console.log(person2.age); //25
// static 멤버에 접근하기
console.log(Person.numberOfPersons); // 2
const person3 = Person.createPerson("Alice", "Johnson", 28);
console.log(Person.numberOfPersons); // 3