interface IFirstInterface {
id: number
}
interface ISecondInterface {
name: string
}
// 다중 Class 상속은 미지원(C++ 지원), 다중 인터페이스 상속은 지원
class MultipleInterfaces implements IFirstInterface, ISecondInterface {
id: number;
name: string;
}
다중상속의 문제
다중 상속의 문제라기보다는 다중 상속을 사용하는 사람들의 문제
코드의 재활용에만 포커싱하여 개발하다보면 계층 관계를 깰 수 있음
class A
class B extends A
class C extends A
class D extends B, C (???)
다이아몬드 계층 이슈
변수의 중복 선언
어떤 변수를 선택해야할지 모호성
super keyword
class BaseClassWithConstructor {
private id: number;
constructor(_id: number) {
this.id = _id;
}
}
class DerivedClassWithConstructor extends BaseClassWithConstructor {
private name: string;
constructor(_id: number, _name: string) {
super(_id);// 부모 클래스 생성자 호출, 필수로 호출해야함
this.name = _name;
}
}
Function overloading
기존 함수에 추가(over)하여 기능을 더하는(load) 것
class BaseClassWithFunction {
public id: number;
getProperties(): string {
return `id: ${this.id}`
}
}
class DerivedClassWithFunction extends BaseClassWithFunction {
public name: string;
getProperties(): string {
// super 를 이용해 부모클래스의 함수 호출 -> 기존 기능에 추가(over)하여 기능 더하는 것 (load) 그래서 오버로딩
return `${super.getProperties()}, $name: ${this.name}`;
}
}
Protected Class members
class ClassUsingProtected {
protected id: number;
public getId() {
return this.id;
}
}
class DerivedFromProtected extends ClassUsingProtected {
public constructor() {
super();
this.id = 0;// 상속받은 클래스는 부모 클래스의 protected 멤버에 접근 가능, 그 외에는 private 처럼 외부 접근 불가
}
}
Abstract Classes
interface 와 유사
Interface 를 이용해 Instance 생성 불가
함수 구현을 할 수도 있음
abstract class AbstractEmployee {
public id: number;
public name: string;
abstract getDetails(): string;// 구현체가 없는 함수 지정
public printDetails() {
console.log(this.getDetails());
}
}
class NewEmployee extends AbstractEmployee {
// 다른 부분은 AbstractEmployee 것을 그대로 쓰고, getDetail 만 구현함
getDetails(): string {
return `id: ${this.id}, name : ${this.name}`;
}
}
class NewManager extends NewEmployee {
public Employees: Employee[];
getDetails(): string {
return super.getDetails() + `, employeeCount ${this.Employees.length}`;
}
}
JavaScript Closures
실행된 Context 를 기억하는 메서드
module pattern을 통한 지역변수 관리
function TestClosure(value) {
this._value = value;
function printValue() {
console.log(this._value);
}
return printValue;
}
var myClosure = TestClosure(12);
myClosure();// 12 를 반환
위와 같은 closure 특성은 TS 컴파일러에서 변환해주는 JS 파일에서 찾아볼 수 있다.
var BaseClassWithConstructor = (function() {
function BaseClassWithConstructor(_id) {
this.id = _id;
}
return BaseClassWithConstructor;
})();//IIFE (Immediately Invoked Function Expression)
extends
를 이용하여 상속 클래스를 구현한다.Interface Inheritance
Class inheritance
다중상속의 문제
다이아몬드 계층 이슈
super
keywordFunction overloading
기존 함수에 추가(over)하여 기능을 더하는(load) 것
Protected Class members
Abstract Classes
interface 와 유사
JavaScript Closures
실행된 Context 를 기억하는 메서드 module pattern을 통한 지역변수 관리
위와 같은 closure 특성은 TS 컴파일러에서 변환해주는 JS 파일에서 찾아볼 수 있다.