기존 프로토타입 기반 객체지향 언어보다 클래스 기반 언어에 익숙한 개발자가 보다 빠르게 학습할 수 있는 단순명료한 새로운 문법을 제시하고 있다. 사실 여기서의 클래스도 함수이고 기존 프로토타입 기반 패턴이다.
1. 클래스 정의
ES6 클래스는 클래스 몸체에 메소드만을 포함할 수 있다.
생성자 (constructor) 내부에서 클래스 프로퍼티를 선언하고 초기화한다.
// person.js
classPerson {
constructor(name) {
// 클래스 프로퍼티의 선언과 초기화
this.name=name;
}
walk() {
console.log(`${this.name} is walking.`);
}
}
Typescript 클래스는 클래스 몸체에 클래스 프로퍼티를 사전 선언하여야 한다.
// person.ts
classPerson {
// 클래스 프로퍼티를 사전 선언하여야 한다
name:string;
constructor(name:string) {
// 클래스 프로퍼티수에 값을 할당
this.name=name;
}
walk() {
console.log(`${this.name} is walking.`);
}
}
constperson=newPerson('Lee');
person.walk(); // Lee is walking
2. 접근 제한자
Typescript 클래스는 클래스 기반 객체 지향 언어가 지원하는 접근 제한자(Access modifier) public, private, protected 를 지원하며 의미 또한 기본적으로 동일하다. 접근 제한자를 생략한 클래스 프로퍼티와 메소드는 암묵적으로 public이 선언된다.
classFoo {
publicx:string;
protectedy:string;
privatez:string;
constructor(x:string, y:string, z:string) {
// public, protected, private 접근 제한자 모두 클래스 내부에서 참조 가능하다.
this.x=x;
this.y=y;
this.z=z;
}
}
constfoo=newFoo('x', 'y', 'z');
// public 접근 제한자는 클래스 인스턴스를 통해 클래스 외부에서 참조 가능하다.
console.log(foo.x);
// protected 접근 제한자는 클래스 인스턴스를 통해 클래스 외부에서 참조할 수 없다.
console.log(foo.y);
// error TS2445: Property 'y' is protected and only accessible within class 'Foo' and its subclasses.
// private 접근 제한자는 클래스 인스턴스를 통해 클래스 외부에서 참조할 수 없다.
console.log(foo.z);
// error TS2341: Property 'z' is private and only accessible within class 'Foo'.
classBarextendsFoo {
constructor(x:string, y:string, z:string) {
super(x, y, z);
// public 접근 제한자는 자식 클래스 내부에서 참조 가능하다.
console.log(this.x);
// protected 접근 제한자는 자식 클래스 내부에서 참조 가능하다.
console.log(this.y);
// private 접근 제한자는 자식 클래스 내부에서 참조할 수 없다.
console.log(this.z);
// error TS2341: Property 'z' is private and only accessible within class 'Foo'.
}
}
3. 생성자 파라미터에 접근 제한자 선언
기존 방식
// person.ts
classPerson{
name:string;
constructor(name:string) {
this.name=name;
}
}
constman=newPerson("kim");
console.log(man.name);// kim
생성자 파라미터에 접근 제한자 사용
// person.ts
classPerson{
// 접근 제한자가 선언된 생성자 파라미터 x는 클래스 프로퍼티로 선언되고 지동으로 초기화된다.