Skip to content

Commit eb09abb

Browse files
committed
🚩: public, private, protected의 접근 제한자의 개념
1 parent 1d07f39 commit eb09abb

File tree

1 file changed

+28
-5
lines changed

1 file changed

+28
-5
lines changed

src/index.ts

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,35 @@
1+
//접근 제한자(Access modifier) - public, private, protected / es6에서는 접근 제한자를 지원하지 않았다 하지만 ts에서는 제공해준다.
2+
13
class Car {
2-
// color: string; //-> 생성자에서 this를 사용하기 위해서는 사용될 변수 프로퍼티를 먼제 선언 해야한다.
3-
// 하지만 프로퍼티를 선언하지 않고 사용하는 방법이 public과 readonly를 해당 매개변수에 지정해주면 된다.
4-
constructor(readonly color: string) {//public
4+
name: string = "car";
5+
color: string;
6+
constructor(color: string) {
57
this.color = color;
68
}
7-
start() {
9+
start(): void {
810
console.log("start");
911
}
1012
}
1113

12-
const bmw = new Car("red");
14+
class Bmw extends Car {
15+
constructor(color: string) {
16+
super(color);
17+
}
18+
showName(): void {
19+
// console.log(super.name); //-> error 이유는 super는 부모 클래스 메서드를 호출 할 때 사용된다. 부모 속성에 접근하려면 this를 사용해야 한다. 즉, constructor에서 사용한 방식과 달리 this를 사용해야한다. 이미 extends Car를 상속받고 있기 때문이다.
20+
console.log(this.name);
21+
// - private: 부모 name이 private인 경우 error가 나온다. 추가적으로 '#name'은 private로 인식한다.
22+
// - protected: 부모 name이 protected인 경우 정상 동작한다. 그렇다면 public과 차이는 무엇인가.
23+
/*
24+
* new를 통해서 인스턴스 했을 경우 접근을 제한하게 된다. 즉, 자식 클래스에서는 부모 속성에 접근을 할 수 있으나 new 인스턴스인 경우 접근이 불가하다.
25+
*/
26+
// - readonly: new 인스턴스를 통해서 값을 변경할 수 없다. 그렇다면 어떻게 해야 변경을 할 수 있을까?
27+
/*
28+
* 부모 constructor 내부에서 작업을 해야한다.
29+
*/
30+
}
31+
}
32+
33+
const z4 = new Bmw("black");
34+
console.log(z4.name);
35+
z4.name = "test";

0 commit comments

Comments
 (0)