[TypeScript] 클래스

종현·2023년 12월 28일

[TypeScript]

목록 보기
8/19

클래스란?

  • 여러 가지 유사한 객체를 쉽게 생성하는 자바스크립트 최신 문법(ES6+)

생성자 함수

  • 함수의 첫 글자를 대문자로 작성한다.

  • new 키워드를 붙여 호출하면 새로운 객체를 생성해준다.

function Peron(name, skill) {
  this.name = name;
  this.skill = skill;
}

const me = new Person('jonghyun', 'TypeScript');


// 위 생성자 함수를 class문법으로 작성한 코드
class Person {
  constructor(name, skill) {
    this.name = name;
    this.skill = skill;
  }
}

클래스 기본 문법

  • Person클래스 코드는 name과 skill값을 받아 객체를 생성할 수 있게 생성자 메서드(constructor)를 선언하고, sayHi()라는 클래스 매서드(class method)를 선언한 코드이다.

  • name과 skill 속성을 클래스 필드(class field) 또는 클래스 속성(class property)하고 한다.

function Peron(name, skill) {
  this.name = name;
  this.skill = skill;
}

Person.prototype.sayHi = fuction() {
  console.log('hi');
}

const me = new Person('jonghyun', 'TypeScript');
me.name // jonghyun
me.sayHi(); // hi

// 위의 코드를 class문법으로 작성한 코드
class Person {
  constructor(name, skill) {
    this.name = name;
    this.skill = skill;
  }
  
  sayHi() {
    console.log('hi');
  }
}
  • 아래 코드처럼 클래스로 생성된 객체를 클래스 인스턴스(class instance)라고 한다.
const me = new Person('jonghyun', 'TypeScript');

클래스의 상속

  • 부모 클래스의 속성과 메서드 등을 자식 클래스에서도 사용할 수 있게 물려준다는 의미

  • 상속을 하면 클래스 인스터스뿐만 아니라 자식 클래스 내부에서도 부모 클래스의 속성이나 메서드를 접근할 수 있다.

class Person {
  constructor(name, skill) {
    this.name = name;
    this.skill = skill;
  }
  
  sayHi() {
    console.log('hi');
  }
}

class Developer extends Person{
  constructor(name, skill) {
    super(name, skill);
    this.sayHi();
  }
  
  coding() {
    console.log(`my name is ${this.name}, my position is ${this.skill}`);
  }
}

const me = new Developer('jonghyun', 'frontend');
me.coding(); // fun
me.sayHi(); // hi
console.log(me.name); // jonghyun

타입스크립트의 클래스

class Chatgpt {
  nams: string;
  
  constructor(name: string) {
    this.name = name
  }
  
  sum(a: number, b: number): number {
    return a + b;
  }
}

클래스 접근 제어자

  • 클래스 속성의 노출 범위를 정의할 수 있는 접근 제어자(access modifier)는 복잡한 기능을 구현할 때 유용하게 쓰인다.

  • 클래스를 정의할 때 어떤 속성이나 메서드를 외부에 노출시킬지 정의할 수 있다.

클래스 접근 제어자

  • public

    • 클래스 안에 선언된 속성과 메서드를 어디서든 접근할 수 있게 한다.

    • 별도로 선언하지 않으면 기본값은 public이다.

  • private

    • 클래스 코드 외부에서 클래스의 속성과 메서드를 접근할 수 없다.

    • public과 반대로 외부와 단절시켜 보호할때 사용한다.

    • 타입스크립의 접근 제어자가 지정되어 있더라도 실행 시점의 에러까지는 보장해 주지 못한다.

      • 따라서 ECMA2020 에 스펙으로 지정된 타입스크립트 3.8버전부터 사용할 수 있는 (#)을 private대신 붙여 사용할 수 있고, 이 문법을 사용하려면 타입스크립트 config파일의 target속성을 2015이상으로 변경 해주어야한다.
class Person {
  // 실행 시점의 에러까지 보장해주려면 private대신 #을 사용하면 된다.
  #name: string;
  #position: string;
  
  constructor(name: string, position: string) {
    this.#name = name;
    this.#position = position;
  }
}

const me = new Person('jonghyun', 'frontend');
console.log(me.#name) // 에러 발생
  • protected

    • private과 비슷하면서 다르다.

    • 선언된 속성이나 메서드는 외부에서 사용할 수 없다. 하지만 상속받은 클래스에서는 사용할 수 있다.

class Person {
  name: string; 
  skill: string;
  
  constructor(name: string, skill: string) {
    this.name = name;
    this.skill = skill;
  }
  
  protected sayHi(): void {
    console.log('hi');
  }
}

class Developer extends Person {
  constructor(name: string, skill: string) {
    super(name, skill);
    // 자식 클래스에서 상속받은 부모의 protected로 만들어진 메서드에 접근이 가능하다.
    this.sayHi();
  }
  
  position() {
    console.log(`my name is ${this.name} and my position is ${this.skill}`)
  }
}

const me = new Developer('jonghyun', 'frontend') // hi
me.position(); // my name is jonghyun and my position is frontend

출처: 쉽게 시작하는 타입스크립트

profile
지속 가능한 성장 습관을 만들어 나가고 싶어요!

0개의 댓글