TypeScript学習5(Classes)
Classes
Blueprint to create an object with some fields (values) and methods (functions) to represent a 'thing'.
class Vehicle { drive(): void { console.log('chugga chugga'); } honk(): void { console.log('beep'); } } class Car extends Vehicle { drive(): void { console.log('vroom'); } } const car = new Car(); car.drive(); car.honk();
上記のようにES2015のClassと同様に働くが、TSならではのmodifierが存在する。
Modifiers
public
This method can be called anywhere, anytime.
private
This method can only be called by other methods in this
class.
privateは決してセキュリティ目的で使用されるものではなく、メソッドが使用されるスコープを制限するためだからである。
protected
This method can be called by other methods in this
class, or by other methods in child classes.
classのメソッドを継承先で使用したいときに使う。
使用例
class Vehicle { constructor(public name: string) { this.name = name; // 省略可 } protected honk(): void { console.log('beep'); } } class Car extends Vehicle { private drive(): void { console.log('vroom'); } startDriving(): void { this.drive(); this.honk(); } } const car = new Car('Beatle'); console.log(car.name); car.startDriving();
継承
class Vehicle { constructor(public name: string) { this.name = name; // 省略可 } protected honk(): void { console.log('beep'); } } class Car extends Vehicle { constructor(public wheels: number, name: string) { super(name); } private drive(): void { console.log('vroom'); } startDriving(): void { this.drive(); this.honk(); } } const car = new Car(4, 'Beatle'); console.log(car.name); car.startDriving();
まとめ
Interfaces + Classes = How we get really strong code reuse in TS