Skip to content

Latest commit

 

History

History
75 lines (53 loc) · 1.52 KB

접근지정자.md

File metadata and controls

75 lines (53 loc) · 1.52 KB

접근 제어자 (Access Modifiers)

  • 종류: public, private, protected
  • 기본값: public
  • 클래스 내부의 모든 곳에 (생성자, 프로퍼티, 메서드) 설정 가능
  • private 으로 설정하면 클래스 외부에서 접근 불가능
  • 자바스크립트에서 private 지원하지 않아 오랜동안 프로퍼티나 메서드 이름 앞에 _ 를 붙여서 표현했음

public

: 어디서든지 접근 가능

class Person {
  public name: string = "Mark";
  public age!: number;

  public constructor(age?: number) {
    if (age === undefined) {
      this.age = 20;
    } else {
      this.age = age;
    }
  }
  public async init() {}
}

const p1: Person = new Person(39);
console.log(p1);
console.log(p1.age);

private

: 외부에서 접근 불가능

private _age!: number;

console.log(p1.age) 사용 불가능

→ 오랫동안 지켜 온 습관 때문에 private 사용 시 메소드에 _ 붙이는 경우 있음

protected

: 외부에서 접근 불가능, 상속 관계에서는 접근 가능


initialization in contructor parameters

class Person {
  public constructor(public name: string, age: number) {}
}

const p1: Person = new Person("Mark", 39);
console.log(p1);

class Person { name: string, age: number; }와 같은 기능


class Person {
  public constructor(public name: string, private age: number) {}
}

const p1: Person = new Person("Mark", 39);
console.log(p1);

→ 접근지정자 추가로 사용 가능