// 類里面的修飾符 typescript提供三種修飾符
/*
public: 公有 在類里面、類外面、子類都可以訪問 (默認不加就是public)
protected: 保護 在類里面和子類可以訪問
private: 私有 在當前類可以訪問別的都不可以訪問
*/
// 類的靜態屬性 靜態方法
/* es5中的寫法 */
function Person () {
// this.run = function () {} // 實例方法
// this.run = ()=> {}
}
Person.run = function () {} // 靜態方法
class Person1 {
name:string;
static sex = 'man'; // 靜態屬性
constructor(name: string) {
this.name = name;
}
eat() {
console.log(`${this.name}吃飯`)
}
static work() {
console.log(`這是一個靜態方法` + Person1.sex)
// console.log(`${this.name}哈哈`) // 錯誤的寫法,靜態方法里面無法調用類的屬性、方法。
}
}
var p = new Person1('aaa');
p.eat(); // 實例方法調用
Person1.work(); // 靜態方法調用
// 多態:父類定義一個方法不去實現,讓繼承它的子類去實現
// typescript中的抽象類是提供其它類的基類,不能直接被實例化;
// 用abstract關鍵字定義的抽象方法和抽象類,不包括具體實現必須在派生類實現。
// 並且抽象方法只能放在 抽象類里面
// 抽象類用於定義標准
abstract class Animal {
abstract eat():void;
}
// var a = new Animal(); // 錯誤的寫法抽象類不能被實例化。
class Dog extends Animal {
constructor() {
super()
}
eat () {
console.log('抽象類的子類必須實現抽象類的抽象方法')
}
}