타입스크립트 static 속성 예제
타입스크립트( Typescript )에서 `static` 속성은 클래스 자체에 속하는 속성이다.
일반 속성은 `new`로 객체를 만들면 각각의 객체가 자신의 값을 가지지만, `static` 속성은 클래스에 그냥 존재하는 형태를 가진다.
굳이, `new`를 사용해 객체화 하지 않아도 속성을 사용할 수 있다.
`객체명.속성명`이 아니라 `클래스명.속성명` 형태로 접근할 수 있다.
기본 문법은 `static 속성명 = 값` 형태이다.
⊙
/* static 속성 */
클래스명.속성명
/* 인스턴스 속성 */
객체명.속성명⊙
class Example {
static message: string = "Hello";
}
console.log(Example.message);⊙
class Website {
static siteName: string = "TypeScript Study";
}
console.log(Website.siteName);⊙
const website = new Website();
/* 오류 발생 */
console.log(website.siteName);⊙
class User {
static count: number = 0;
name: string;
constructor(name: string) {
this.name = name;
/* 객체가 생성될 때마다 공통 count 증가 */
User.count++;
}
}
const user1 = new User("민수");
const user2 = new User("지영");
const user3 = new User("현우");
console.log(User.count);⊙
class Product {
static category: string = "전자제품";
name: string;
constructor(name: string) {
this.name = name;
}
}
const product1 = new Product("노트북");
const product2 = new Product("모니터");
console.log(Product.category);
console.log(product1.name);
console.log(product2.name);⊙
class Counter {
static count: number = 0;
}
Counter.count++;
console.log(Counter.count);⊙
???⊙
???⊙
???⊙
???⊙
???⊙
???⊙
???⊙
???⊙
???⊙
???⊙
???⊙
???⊙
???
댓글
댓글 쓰기