Skip to content

Commit 7fe944d

Browse files
committed
🚩: static에 대한 개념과 사용 방법
1 parent 4ea5605 commit 7fe944d

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

src/index.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,16 @@
33
class Car {
44
readonly name: string = "car";
55
color: string;
6+
static wheels = 4;
67
constructor(color: string, name: string) {
78
this.color = color;
89
this.name = name;
910
}
1011
start(): void {
1112
console.log("start");
13+
console.log(this.name);
14+
// console.log(this.wheels); //-> error : this가 아닌 class 이름으로 접근
15+
console.log(Car.wheels);
1216
}
1317
}
1418

@@ -18,7 +22,6 @@ class Bmw extends Car {
1822
// 참고로 'super()'는 부모(일반적인 super가 아님)의 constructor에 접근
1923
}
2024
showName(): void {
21-
// console.log(super.name); //-> error 이유는 super는 부모 클래스 메서드를 호출 할 때 사용된다. 부모 속성에 접근하려면 this를 사용해야 한다. 즉, constructor에서 사용한 방식과 달리 this를 사용해야한다. 이미 extends Car를 상속받고 있기 때문이다.
2225
console.log(this.name);
2326
// - private: 부모 name이 private인 경우 error가 나온다. 추가적으로 '#name'은 private로 인식한다.
2427
// - protected: 부모 name이 protected인 경우 정상 동작한다. 그렇다면 public과 차이는 무엇인가.
@@ -29,9 +32,12 @@ class Bmw extends Car {
2932
/*
3033
* 부모 constructor 내부에서 작업을 해야한다.
3134
*/
35+
// - static: static은 정적 맴버 변수를 만들어 줄 수 있다. static에 접근을 하기 위해서는 this가 아닌 class 이름으로 접근을 해야 한다.
3236
}
3337
}
3438

3539
const z4 = new Bmw("black", "test");
3640
console.log(z4.name);
37-
// z4.name = "test"; // error -> 현재 name은 readonly이기 때문에 인스턴스 생성자에서 변경을 해야한다.
41+
// z4.name = "test";
42+
// console.log(z4.wheels); //-> error : this가 아닌 class 이름으로 접근
43+
console.log(Car.wheels);

0 commit comments

Comments
 (0)