[TypeScript] class 문법 접근 제한자 (public, private)

gu·2023년 8월 12일

TypeScript

목록 보기
4/13

🔍 class

class 접근 제한자를 알아보기전에 class에 대해 간단하게 알아보자.
class: es6에 새롭게 도입된 클래스는 기존 프로토 타입 기반 객체지향 언어보다 클래스 기반 언어에 익숙한 개발자가 빠르게 학습할 수 있는 단순명료한 새로운 문법을 제시하고 있다. 하지만 클래스가 새로운 객체지향 모델을 제공하는 것은 아니다. 사실 클래스도 함수이고 기존 프로토타입 기반 패턴의 syntactic sugar일 뿐이다. TypeScript가 지원하는 클래스는 es6클래스와 상당히 유사하지만 몇 가지 TypeScript만의 고유한 확장 기능이 있다.

📌 ES6 class

es6클래스는 클래스 몸체에 메소드만을 포함할 수 있다. 클래스 몸체에 클래스 프로퍼티를 선언할 수 없고 반드시 생성자 내부에서 클래스 프로퍼티를 선언하고 초기화한다.

class User{
	constructor(name){
    // 클래스 프로퍼티 선언과 초기화
    this.name = name;
    }
    students(){
      console.log(`${this.name} is student.`);
  }
}

위 코드는 es6에서 문제없지만 ts로 변경할 시 컴파일하면 컴파일에러가 발생한다.

📌 TypeScript class

TypeScript 클래스는 클래스 몸체에 클래스 프로퍼티를 사전 선언해야한다.

class User{
  name:string;
	constructor(name){
    // 클래스 프로퍼티 선언과 초기화
    this.name = name;
    }
    students(){
      console.log(`${this.name} is student.`);
  }
}
const school = new User('철수');
school. students // output: '철수 is student.'

❗public / readonly를 사용해주면 member변수를 미리 선언하지 않아도 된다.

🔍 접근제한자

  • 클래스 기반 객체 지향 언어가 지원하는 접근 제한자 (Access modifier)
  • 접근제한자를 명시하지 않았을때
    ㅇ 다른클래스 기반 언어: protected로 지정
    ㅇ typescript: public으로 지정

📌 private / public / protected

접근 가능성publicprotectedprivate
클래스 내부
자식클래스 내부X
클래스 인스턴스XX

// private을 붙이면 class{}안에서만 사용가능
// protected을 붙이면 현재 class{}안에서 + extends된 class{}안에서 사용가능
class User {
  protected x=10;
}
class NewUser extends User {
 doThis(){
   
   this.x=20;
 }
}

let 사람 = new NewUser()
console.log(사람)

  • protected: extends된 class는 사용가능, 자식들 사용불가능
  • private: extends된 class는 사용불가능, 자식들 사용불가능
  • static: 부모 class에 직접 부여됨(자식들은 사용불가능능)
  • private/protected/public+static가능
class Foo {
  public x : string;
  protected y : string;
  private z : string;
  
  constructor(x:string,y:string,z:string) {
    // public,protected,private **모두 클래스 내부에서 참고 가능.**
    this.x=x;
    this.y=y;
    this.z=z;
  }
}
// 클래스 인스턴스를 통해 클래스 외부 참조
const foo = new Foo('x','y','z');
console.log(foo.x); // 참조 가능
console.log(foo.y); // 참조 불가능
console.log(foo.z); // 참조 불가능

// 자식 클래스 내부에 참조
class Bar extends Foo {
  constructor(x:string,y:string,z:string) {
    super(x,y,z);
    console.log(this.x); // 참조 가능
    console.log(this.y); // 참조 가능
    console.log(this.z); // 참조 불가능

⚡생성자 파라미터에 접근 제한자 선언

  • 생성자 파라미터에도 접근 제한자를 선언할 수 있다.
  • 접근 제한자가 사용된 생성자 파라미터는 암묵적으로 클래스 프로퍼티로 선언되고 생성자 내부에서 별도의 초기화가 없어도 암묵적으로 초기화가 수행된다.
class Foo {
  // public으로 x는 클래스 외부에서도 참조가 가능하다.
  constructor(public x:string) {}
}
const foo = new Foo('Hello');
console.log(foo); // Foo {x:'Hellow'}
console.log(foo.x); // Hello

class Bar {
  // private으로 클래스 내부에서만 참조 가능하다.
  constructor(private x:string) {}
}
const bar = new Bar('Hello');
console.log(bar); // Bar {x:'Hello'}
console.log(bar.x); // 참조 불가
  • 만약 생성자 파라미터에 접근제한자를 선언하지 않으면 생성자 내부에서만 유효한 지역변수가 되어 외부에서 참조 불가능하다.

📌 static

  • static으로 선언된 정적 변수는 this가 아닌 클래스명으로만 접근이 가능하다.
  • 클래스의 인스턴스를 생성하지 않아도 호출할 수 있다.
class Age{
  static a = 10;
  b=11;
}
let 자식 = new Age()
console.log(자식) // b만 콘솔에서확인가능
  • Typescript에서는 static 키워드를 클래스 프로퍼티에도 사용할 수 있다.
class Foo {
  static instanceCounter = 0;
  constructor() {
    // 생성자가 호출될 때마다 카운터를 1씩 증가시킨다.
    Foo.instanceCounter++;
  }
}
var foo1 = new Foo();
var foo2 = new Foo();
console.log(Foo.instanceCounter); //2
console.log(foo2.instanceCounter); // error

⭐ static 활용

class Person{
  static skill='js';
  // this.skill불가 부모만이올수있음
  intro=Person.skill+'전문가입니다';

}
let 짱구 = new Person()
console.log("짱구: ",짱구.intro) // 짱구:  js전문가입니다
Person.skill='ts';
let 유리 = new Person()
console.log("유리: ",유리.intro) // 유리:  ts전문가입니다

참고

[Typescript] 클래스(Class) : private, protected, public
12.4 TypeScript - Class

0개의 댓글