// export 可以讓其他 ts 檔案去引用
// void 是不回傳值的型別
export interface AnimalInterface {
hp: number;
call(): void;
}
// AnimalConstructor 是 [new 物件(參數),物件型別是 AnimalInterface] 的型別
export type AnimalConstructor = new(hp: number) => AnimalInterface;
// 調用新增物件的方法, createAnimal(要被 new 的物件,物件參數)
export function createAnimal(ani: AnimalConstructor, hp: number): AnimalInterface {
return new ani(hp);
}
// Human 要實作 AnimalInterface 的內容
export class Human implements AnimalInterface {
// 有 public 可以讓 html檔 的 物件讀取到屬性(private 其實也可以讀取到,但就會有毛毛蟲)
constructor(public hp: number) { }
call(): void {
alert('水之呼吸' + this.hp + '分貝');
console.log('水之呼吸');
}
}
export class Dog implements AnimalInterface {
// 添加 public 等同宣告 key 並把值帶入 key (比較簡約的寫法但是要注意 public private 讀取性問題)
constructor(public hp: number) { }
call(): void {
alert('旺旺' + this.hp + '分貝');
console.log('旺旺');
}
}
可以先無視
- 補充對照組,兩個效果相同差在毛毛蟲// AnimalConstructor型別 是 [new 物件(參數),物件型別是 AnimalInterface]
export type AnimalConstructor = new(hp: number) => AnimalInterface;
// 有毛毛蟲版本 跟上面的 AnimalConstructor 對比
export interface AnimalConstructor {
new(hp: number): AnimalInterface;
}
<button type="button" (click)="peopleCall()">人的聲音</button>
<button type="button" (click)="dogCall()">狗的聲音</button>
import { Component, OnInit } from "@angular/core";
import { createAnimal, Human, Dog } from "./animal.model";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.scss"]
})
export class AppComponent implements OnInit {
human = createAnimal(Human, 100);
dog = createAnimal(Dog, 20);
peopleCall(): void {
this.human.call();
}
dogCall(): void {
this.dog.call();
}
}