class, constructor 예약어!
class Department {
name: string;
constructor(n: string) {
this.name = n;
}
}
const accounting = new Department("ACCOUNTING");
console.log(accounting.name);
JS에서 Class의 개념은 ES6에 등장한 새로운 개념은 아니다. 기존에도 Class의 개념은 존재했지만 그 표현방식이 달랐기 때문에 다른 프로그래밍 언어를 사용하는 이들에게 혼란을 줄 수 있었다. 이를 해결하기 위해 ES6에서 그 표현법이 달라진 것이지 이전에도 존재한 개념이었다.
"use strict";
var Department = /** @class */ (function () {
function Department(n) {
this.name = n;
}
return Department;
}());
var accounting = new Department("ACCOUNTING");
console.log(accounting.name);
class Department {
constructor(n) {
this.name = n;
}
}
const accounting = new Department("ACCOUNTING");
console.log(accounting.name);
this는 생성된 클래스의 구체적인 인스턴스를 참조한다.
아래와 같이 메소드에 접근할 경우, undefined를 띄운다.
const tmpAcc = { describe: accounting.describe };
tmpAcc.describe(); // => department: undefined
이를 방지하기 위해 class 내부에 메소드 선언부에 this:클래스명 형식으로 타입을 선언해주면 this에 해당하는 클래스의 명세에 맞지 않는 객체가 해당 메소드를 호출하면 에러를 띄운다.
describe(this: Department) {
console.log("department:", this.name);
}
JS는 최근까지 기본적으로 public으로 접근제어자가 설정되어있다. 이를 TS에서는 private으로 지정해준다(JS의 최근 문법에서는 변수 앞에 #를 붙여줌으로써 이를 구현할 수 있다). 이는 JS의 런타임에 체크하는것이 아닌 컴파일 중 에러를 띄워 방지해준다.
(private, get, set 참고: https://ko.javascript.info/private-protected-properties-methods)
class Department {
public name: string;
private employees: string[] = [];
...
}
기본적으로 propety를 선언 후 constructor 안에서 this.propertyThing = ~~로 할당해주는 이중 초기화 방식을 constructor 선언부에서 접근제어자, property명, type을 명시해주는 것으로 간소화할 수 있다. 이를 약식 초기화라고 한다.
class Department {
public id: string;
private name: string;
private employees: string[] = [];
constructor(id: string, n: string) {
this.id = id;
this.name = n;
}
...
}
위의 코드에서는 이중 초기화로 class 필드에 property를 선언 후 초기화를 직접 두 번 코드에 작성해준다. 이를 아래와 같이 약식 초기화할 수 있다.
class Department {
// public id: string;
// private name: string;
private employees: string[] = [];
// constructor(id: string, n: string) {
// this.id = id;
// this.name = n;
// }
constructor(public id: string, private name: string) {
// this.id = id;
// this.name = n;
}
}
const testObj = new Department("id1", "Otter");
초기화 이후에 변경되어서는 안되는 데이터에 대해 readonly 키워드를 더해주면 된다. TS에서만 에러를 체크해준다. 초기화 이후 값을 변경하려고 하면 에러를 띄운다.