6-1. 자바스크립트의 클래스 소개
/** ES6 Class */
class Student {
// constructor
constructor(name, grade, age) {
// fields(properties)
this.name = name;
this.grade = grade;
this.age = age;
}
// methods
study() {
console.log("study");
}
introduce() {
console.log("hi i'm", this.name);
}
}
// Student Instance
let studentA = new Student("kihoon", "B", 25);
console.log(studentA);
studentA.study()
studentA.introduce();
class DeveloperStudent extends Student {
constructor(name, grade, age, favoriteSkill) {
// fields, using super
super(name, grade, age);
this.favoriteSkill = favoriteSkill;
}
// methods
writeCode() {
console.log(`${this.name} writing code using ${this.favoriteSkill}`);
}
}
// DeveloperStudent Instance
const studentB = new DeveloperStudent('kihoon', 'B', 25, 'TypeScript');
studentB.study();
studentB.introduce();
studentB.writeCode();
class 키워드를 통해 클래스를 정의할 수 있으며, class 내부에서는..
- this를 통해 클래스의 필드를 지정할 수 있고,
- 생성자 함수를 정의하여 필드에 값을 저장할 수 있다.
- 메소드 역시 정의할 수 있다.
new 키워드를 통해 생성자 함수를 호출하여 클래스의 인스턴스 객체를 생성할 수 있다.
- TypeScript와 동일하게
extends 키워드를 사용하여 다른 클래스를 상속할 수 있다.
- 기존 생성자 함수의 내용을 가져오기 위해서는
super() 함수를 사용할 수 있다.
- 확장한(상속한) 클래스에서는 추가 필드와 메소드를 정의할 수 있다.
- 확장한 클래스의 인스턴스는 기존 필드 및 메소드에 더해 추가된 필드 및 메소드를 사용할 수 있다.
JS 클래스에 더 공부해 보려면..
PoiemaWeb
Classes - JavaScript | MDN
6-2. 타입스크립트의 클래스
/** TS Class */
class Employee {
// fields
name: string;
age: number;
position: string;
// constructor
constructor(name: string, age: number, position: string) {
this.name = name;
this.age = age;
this.position = position;
}
// methods
work() {
console.log("work");
}
}
const employeeA = new Employee("kihoon", 25, "FE Engineer");
console.log(employeeA);
const employeeB: Employee = {
name: "kihoon",
age: 25,
position: "FE Engineer",
work() {},
};
class Manager extends Employee {
// fields
officeNumber: number;
// constructor
constructor(name: string, age: number, position: string, officeNumber: number) {
super(name, age, position);
this.officeNumber = officeNumber;
}
}
- 클래스 기본 요소들은 JS와 다를 바가 없다.
- 다른 점이 있다면 필드 변수들의 타입을 지정해 주어야 한다는 것,
- 그리고 타입 체킹이 더 엄격하게 이루어지기 때문에 더 안전하게 클래스를 사용할 수 있다는 점 등이 있다.
- 예를들어 필드를 선언하고나서 값을 할당하지 않으면(초기값을 할당하거나 constructor함수 안에서 인자값을 할당해주어야 함), 에러가 발생한다. (JS에서는 그렇지는 않다)
- 그리고 상속 클래스(
extends를 사용하는 클래스)의 생성자에서 super를 사용하지 않으면 역시 에러가 발생한다.
6-3. 접근 제어자 access modifier
- 이제 JS에는 없고 TS에만 있는 클래스 요소들을 알아보자.
- 접근 제어자를 통해 외부에서 클래스 내부 요소에 접근할 수 있는지 여부를 제어할 수 있다.
public, private, protected 세가지가 있다. 알아보자.
/** 접근 제어자 access modifier */
class Employee {
// // fields
// public name: string;
// private age: number;
// protected position: string;
// // constructor
// constructor(name: string, age: number, position: string) {
// this.name = name;
// this.age = age;
// this.position = position;
// }
constructor(
public name: string,
private age: number,
protected position: string
) {}
// methods
work() {
console.log(`${this.age} years old man is working.`);
}
}
const employee = new Employee("kihoon", 25, "FE Engineer");
console.log(employee.name);
// console.log(employee.age); // error
// console.log(employee.position); // error
employee.work();
class ExtendedEmployee extends Employee {
protectedTest() {
console.log(`using ${this.position}`);
}
privateTest() {
// console.log(`using ${this.age}`); // error
}
}
- 접근 제어자를 생성자 함수의 매개변수 사용하는 경우
- 이 경우에는 필드 정의와 중복 사용하면 오류가 발생한다. (따라서 필드 정의를 주석처리 한 모습)
- 그리고 프로퍼티의 초기값을 할당하는 것도 자동으로 처리된다.
- 따라서 더이상 기존 생성자에서
this.name = name; 이 필요 없다. 생성자 함수의 매개변수에 접근 제어자를 사용하게 되면 이 부분 역시 자동으로 이루어진다.
- 따라서 주석처리한 모습이다.
public