문서의 이전 판입니다!
기존의 JavaScript는 재사용 가능한 component를 만들기 위해 함수와 prototype에 기반한 상속을 이용했습니다. 하지만 기존 객체지향에 익숙해 있는 개발자들에게는 상당히 생소한 개념이었죠. 그래서 ECMAScript 2015( ES6 )에서는 개발자들이 좀 더 쉽게 JavaScript Application을 구현할 수 있도록 전통적인 class 기반의 객체지향 개념을 도입했습니다.
TypeScript 역시 이 class기반의 객체지향 기법을 이용해 Application을 개발할 수 있습니다.
일단 ECMAScript 2015( ES6 )의 class는 다음과 같이 정의하고 사용할 수 있습니다.
class Book { constructor(btitle,bauthor) { this.btitle = btitle; this.bauthor = bauthor; } printInfo() { console.log(`제목: ${this.btitle}, 저자: ${this.bauthor}`); } } let book = new Book('젊은 베르테르의 슬픔','괴테'); book.printInfo();
위의 코드는 data type의 정보를 포함하고 있지 않기 때문에 TypeScript로 변형하면 오류가 발생합니다. 적절히 타입 정보를 포함해 코드를 수정하면 다음과 같습니다.
class Book { btitle: string; bauthor: string; constructor(btitle:string, bauthor:string) { this.btitle = btitle; this.bauthor = bauthor; } printInfo(): void { console.log(`제목: ${this.btitle}, 저자: ${this.bauthor}`); } } let book:Book = new Book('젊은 베르테르의 슬픔','괴테'); book.printInfo();
위의 코드는 Java에서 우리가 익히 보아왔던 class의 형태입니다. 생성자를 표현하는 부분이 좀 생소하지만 쉽게 이해할 수 있을 듯 합니다.