TypeScript 시작하기 (16) - class에서 사용가능한 protected, static 키워드

funfungun·2025년 1월 16일

TypeScript 시작하기

목록 보기
16/18
post-thumbnail

지난 시간에는 타입스크립트에서의 public 과 private 키워드에 대해 알아보았습니다. 이번 시간에는 protected 와 static 키워드에 대해 알아보겠습니다.


  1. private 과 유사하게, protected 라는 키워드를 사용할 수 있는데, private 은 확장된 클래스에서는 사용할 수 없지만, protected 는 확장된 클래스에서도 사용할 수 있습니다. 하지만 protected 역시 자식들은 접근이 불가능합니다.

    class User {
      protected x = 10;
    }
    
    class NewUser extends User {
      doThis() {
        this.x = 20;
      }
    }

  1. static 키워드를 붙이면 접근권한이 부모 class 에 직접 부여됩니다. 즉, 자식에게는 상속되지 않습니다.

    class User {
      static x = 10; //부모만 사용가능
      y = 20; //자식만 사용가능
    }
    
    let child = new User();
    console.log(User.x);

  1. static 이 붙은 변수는 this 키워드를 사용할 수 없고, 부모 클래스를 아래와 같이 직접 사용해야 합니다. 사실은 private 키워드를 사용하고, 수정하는 함수를 따로 만드는 것이 더 관례적입니다.

    class User {
      static skill = "js";
      intro = User.skill + " expert";
    }
    
    let chulsu = new User();
    console.log(chulsu);

  1. 참고로 static 은 private, protected, public 키워드와 동시 사용이 가능합니다. 다음 x,y,z 속성의 특징을 생각해봅시다.
    class User {
      private static x = 10;
      public static y = 20;
      protected z = 30;
    }

  1. x 속성에 숫자를 더해주는 함수와, x 값을 콘솔 창에 출력해주는 함수가 필요하다고 가정해봅시다. addOne 함수와 printX 함수를 완성해봅시다. (private static x = 10;은 수정금지.)

    class User {
      private static x = 10;
      public static y = 20;
    }
    
    User.addOne(3);
    User.addOne(4);
    User.printX();
    class User {
      private static x = 10;
      public static y = 20;
    
      static addOne(n: number) {
        User.x += n;
      }
      static printX() {
        console.log(User.x);
      }
    }
    
    User.addOne(3);
    User.addOne(4);
    User.printX();

  1. square.draw() 할 때마다 index.html 에 가로 30px, 세로 30px, 배경색이 'red' 인 <div> 박스가 가로 400px, 세로 400px 안에 무작위로 배치되게 만들어봅시다.

    let square = new Square(30, 30, "red");
    square.draw();
    square.draw();
    square.draw();
    square.draw();
    class Square {
      constructor(
        public width: number,
        public height: number,
        public color: string
      ) {}
      draw() {
        let a = Math.random();
        let square = `<div style="position:relative; 
          top:${a * 400}px; 
          left:${a * 400}px; 
          width:${this.width}px; 
          height : ${this.height}px; 
          background:${this.color}"></div>`;
        document.body.insertAdjacentHTML("beforeend", square);
      }
    }
    
    let square = new Square(30, 30, "red");
    square.draw();
    square.draw();
    square.draw();
    square.draw();

지금까지 타입스크립트에서의 protected 와 static 키워드에 대해 알아보았습니다. 다음 시간에는 타입의 import, export 와 namespace 에 대해 알아보겠습니다.

profile
Commercial Art

0개의 댓글