[TypeScript] 클래스 소개

Yong·2022년 6월 17일
0

TypeScript

목록 보기
3/4

클래스는 자바스크립트의 기존 프로토타입 기반 상속에 대한 문법적 설탕(Syntax sugar)입니다. 클래스 문법이 자바스크립트에 새로운 객체지향 상속 모델을 도입하는 것은 아닙니다.

클래스 정의

타입스크립트에서는 class를 정의할때 다음과 같이 정의할 수 있습니다.

생성자 파라미터의 타입을 지정해주어야 합니다.

class Department {
  name: string;

  constructor(n: string) {
    this.name = n;
  }
}

const accounting = new Department("개발부서");

console.log(accounting);

컴파일된 JavaScript 코드

타입스크립트 코드가 자바스크립트 코드로 컴파일링 되었을때 모습입니다.
먼저 ES6 버전.

class Department {
    constructor(n) {
        this.name = n;
    }
}
const accounting = new Department("개발부서");
console.log(accounting);

다음 ES5 버전

var Department = (function () {
    function Department(n) {
        this.name = n;
    }
    return Department;
}());
var accounting = new Department("개발부서");
console.log(accounting);

this.

class Department {
  name: string;

  constructor(n: string) {
    this.name = n;
  }

  describe() {
    console.log("Department: " + this.name);
  }
}

const accounting = new Department("회계");

accounting.describe(); //Department: 회계

const accountingCopy = { describe: accounting.describe };

accountingCopy.describe(); =>출력: Department: undefined

describe() 함수에 this는 Department라고 명시해주지 않는다면, accountingCopy.describe()를 호출했을때 Department: undefined가 콘솔에 출력될 것입니다.
this는 클래스가 정의되는 곳을 명시하기 때문입니다.

타입스크립트에서는 this를 명시해줌으로써 에러를 감지할 수 있습니다.

  describe(this: Department) {
    console.log("Department: " + this.name);
  }

이 때, accountingCopy.describe(); 이 코드는 에러가 발생하는 코드가 됩니다. 타입스크립트가 감지하게 됩니다.

const accountingCopy = { name: "회계 복사본", describe: accounting.describe };
에러를 고쳐주기 위해서는 객체 안에 name을 추가해주면 describe는 객체 내부에 name 프로퍼티가 어떤것인지 알게 됩니다.

profile
If I can do it, you can do it.

0개의 댓글