[TypeScript-06] public, private

Comely·2025년 6월 6일

TypeScript

목록 보기
6/9

TypeScript Class 키워드 완벽 가이드

1. public, private 키워드

public 키워드

  • 클래스 속성을 어디서든 접근하고 수정 가능하게 만듦
  • 기본값이므로 생략해도 동일하게 작동
class User {
  public name: string;
  
  constructor() {
    this.name = 'kim';
  }
}

let 유저1 = new User();
유저1.name = 'park';  // 가능

private 키워드

  • 클래스 내부에서만 접근하고 수정 가능
  • 자식 객체에서도 접근 불가능
class User {
  public name: string;
  private familyName: string;
  
  constructor() {
    this.name = 'kim';
    let hello = this.familyName + '안뇽';  // 가능 (클래스 내부)
  }
}

let 유저1 = new User();
유저1.name = 'park';        // 가능
유저1.familyName = '456';   // 에러 (외부 접근 불가)

private 속성 수정하기

외부에서 private 속성을 수정하려면 클래스 내부에 함수를 만들어 간접 접근

class User {
  private familyName: string;
  
  changeSecret() {
    this.familyName = 'park';  // 클래스 내부에서 수정
  }
}

let 유저1 = new User();
유저1.changeSecret();  // 함수를 통한 간접 수정

활용법: 중요한 데이터를 실수로 수정하는 것을 방지하고, 안전장치를 추가한 개발 가능

2. Constructor 단축 문법

public/private 키워드를 constructor 파라미터에 붙이면 필드 선언과 할당을 동시에 처리

// 기존 방식
class Person {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
}

// 단축 문법
class Person {
  constructor(public name: string) {
    // this.name = name 자동 생성
  }
}

3. protected 키워드

private와 비슷하지만 extends로 상속받은 클래스에서도 사용 가능

class User {
  protected x = 10;
}

class NewUser extends User {
  doThis() {
    this.x = 20;  // protected라서 가능 (private이면 에러)
  }
}
  • private: 해당 클래스에서만 사용
  • protected: 해당 클래스 + 상속받은 클래스에서 사용

4. static 키워드

속성이나 메서드를 클래스 자체에 부여 (인스턴스가 아닌)

class User {
  static x = 10;  // 클래스에 직접 부여
  y = 20;         // 인스턴스에 부여
}

let john = new User();
john.x;   // 불가능
User.x;   // 가능 (10)
john.y;   // 가능 (20)

static 활용 예시

클래스의 기본 설정값이나 공통 데이터 저장용

class User {
  static skill = 'js';
  intro = User.skill + ' 전문가입니다';
}

// 설정 변경
User.skill = 'python';
let 민수 = new User();  // 'python 전문가입니다'

키워드 조합 사용

class User {
  private static x = 10;     // 클래스 내부에서만 접근 가능한 static
  public static y = 20;      // 어디서든 접근 가능한 static
  protected z = 30;          // 상속 클래스에서도 사용 가능
}

5. 실무 활용 예시

숙제 1: 키워드 특징 정리

class User {
  private static x = 10;    // User 클래스에서만 접근, 수정 가능
  public static y = 20;     // 어디서든 User.y로 접근, 수정 가능
  protected z = 30;         // 클래스 내부 + 상속 클래스에서 사용 가능
}

숙제 2: static 메서드 만들기

class User {
  private static x = 10;
  public static y = 20;
  
  static addOne(param: number) {
    User.x += param;  // static 속성은 클래스명.속성으로 접근
  }
  
  static printX() {
    console.log(User.x);
  }
}

User.addOne(3);
User.printX();  // 13

숙제 3: DOM 조작 클래스

class Square {
  constructor(
    public width: number, 
    public height: number, 
    public color: string
  ) {}
  
  draw() {
    let randomPos = Math.random() * 400;  // 0~400px 랜덤 위치
    
    let square = `<div style="
      position: relative;
      top: ${randomPos}px;
      left: ${randomPos}px;
      width: ${this.width}px;
      height: ${this.height}px;
      background: ${this.color}
    "></div>`;
    
    document.body.insertAdjacentHTML('beforeend', square);
  }
}

let 네모 = new Square(30, 30, 'red');
네모.draw();  // 랜덤 위치에 빨간 사각형 생성

정리

키워드접근 범위설명
public어디서든기본값, 자유롭게 접근 가능
private클래스 내부만외부 접근 차단, 보안성 높음
protected클래스 + 상속 클래스private보다 범위가 넓음
static클래스 자체인스턴스가 아닌 클래스에 직접 부여

핵심: 각 키워드는 데이터 보안과 코드 구조화를 위한 도구들입니다

profile
App, Web Developer

0개의 댓글