본문 바로가기

똑소리-IT/TypeScript

[Typescript] Classes

[Classes]


1. class (클래스)

간단한 class기반의 예제를 살펴보자. 

class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

let greeter = new Greeter("world");


위 코드에서는 3가지 멤버(greeting이라고 불리는 property, constructorgreet() 메소드)를 가지고있는 Greeter Class를 정의하고있다.

참고로 constructor(생성자) 메소드는 class로 생성된 객체를 초기화하기위한 특수 메소드이다.





2. Inheritance (상속)

 상속 예제를 살펴보자

class Animal {
    name: string;
    constructor(theName: string) { this.name = theName; }
    move(distanceInMeters: number = 0) {
        console.log(`${this.name} moved ${distanceInMeters}m.`);
    }
}

class Snake extends Animal {
    constructor(name: string) { super(name); }
    move(distanceInMeters = 5) {
        console.log("Slithering...");
        super.move(distanceInMeters);
    }
}

class Horse extends Animal {
    constructor(name: string) { super(name); }
    move(distanceInMeters = 45) {
        console.log("Galloping...");
        super.move(distanceInMeters);
    }
}

let sam = new Snake("Sammy the Python");
let tom: Animal = new Horse("Tommy the Palomino");

sam.move();
tom.move(34);

 

extends를 사용하여 부모 class로 부터 특정 기능을 상속받을수있다. 

위의 예제의 부모 class는 Animal이 될것이고 자식 class는 Snake와 Horse가 될것이다.


부모 class의 constructor 함수는 super 키워드를 통해 호출할수있으며,

Snake class, Horse class 둘 다 Animal class의 constructor 함수를 호출한것을 확인할수 있다.


따라서 sam.move()는 Snake class의 move함수에서 super.move를 통해 부모 class인 Animal class의 move함수로 이동할것이고 

tom.move(34)는 Horse class의 move함수에서 super.move를 통해 부모 class인 Animal class의 move함수로 이동할것이다.





3. Public, private, and protected modifiers


접근제한자 public, private, protected에대해 알아보도록 한다.

예제를 확인하기전 각각의 기능을 간략하게 구분하면 다음과 같다.


public 

어디에서나 해당 class, method 참조 가능하다.

private

자신을 포함한 class내에서만 참조 가능하다.

protected

자신과 상속받은 class내에서만 참조 가능하다.



class Animal {
    private name: string;
    constructor(theName: string) { this.name = theName; }
}

new Animal("Cat").name; // Error: 'name' is private;


private로 선언한 name을 class 외부에서 호출시도하여 발생한 ERROR이며, 

해당 ERROR를 해결하기위해서는 private를 public으로 수정하거나 제거하면된다. 

( 기본적으로 접근 제한자를 사용하지 않는다면 모든 프러퍼티와 메소드는 public 이다.)


class Person {
    protected name: string;
    constructor(name: string) { this.name = name; }
}

class Employee extends Person {
    private department: string;

    constructor(name: string, department: string) {
        super(name);
        this.department = department;
    }

    public getElevatorPitch() {
        return `Hello, my name is ${this.name} and I work in ${this.department}.`;
    }
}

let howard = new Employee("Howard", "Sales");
console.log(howard.getElevatorPitch());
console.log(howard.name); // error


protected로 선언한 name을 subclass인 Emloyee 에서는 사용가능하지만 그 외 외부에서 접근시 Error가 발생한다.




4. Accessors (접근자)


class Employee {
    fullName: string;
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
    console.log(employee.fullName);
}


Typescript에서 지원하는 get 과 set 에대한 간단한 예제이다.

멤버 fullName에 값을 설정하고 리턴하는 역할을 한다.



5. Abstract Classes (추상화 Class)


abstract class Animal {
    abstract makeSound(): void;
    move(): void {
        console.log("roaming the earth...");
    }
}


추상화 class란 추상 method를 포함하고있는 class를 의미한다.

추상화 class 자체만으로는 인스턴트를 생성할수 없기 때문에 상속을 통해 자식 class에 의해서만 완성될수 있다.


'똑소리-IT > TypeScript' 카테고리의 다른 글

[Typescript] interface  (0) 2017.01.02
[Typescript] Variable Declarations  (0) 2016.12.28
[Typescript] Basic Types  (0) 2016.12.27