課程網(wǎng)站建設(shè)的設(shè)計(jì)報(bào)告google seo 優(yōu)化教程
使用類實(shí)現(xiàn)功能
ts中類的繼承
ES6中class類中,屬性分為:實(shí)例上的屬性,原型上的方法;也可以叫做:class的屬性,class的方法。
類的繼承叫法:父類=>子類,基類=>派生類;它們本質(zhì)上是一樣的。
super指向父類的構(gòu)造函數(shù)
繼承簡(jiǎn)單功能:擴(kuò)展現(xiàn)有的類,通過抽離父類的方式來實(shí)現(xiàn)子類的復(fù)用。(實(shí)現(xiàn)公共方法的抽離,讓子類實(shí)現(xiàn)復(fù)用)。
類上注解實(shí)例上的屬性:
class Greeter {greeting: number; //僅當(dāng)類被實(shí)例化的時(shí)候才會(huì)被初始化的屬性constructor(message: number) {this.greeting = message;}greet(a: number): string {return "Hello, " + this.greeting;}
}
class Greeter1 extends Greeter {constructor() {super(123);}greet(a: number): string {return "Hello, " + this.greeting;}
}
ts中類中的public、private、protected、readonly修飾符
修飾符名稱 | 使用范圍 |
---|---|
public | 自身、子類、實(shí)例 |
private | 自身 |
protected | 自身和子類 |
readonly | 只讀屬性必須在聲明時(shí)或構(gòu)造函數(shù)里被初始化。 |
readonly只會(huì)用在屬性簽名或者索引簽名(簽名是數(shù)字)前面。
簡(jiǎn)寫問題:
類中屬性不寫修飾符,默認(rèn)被public修飾。
class Person {public name: string;constructor(theName: string) {this.name = theName;};sayName(){console.log(this.name, 2);}
}
// 簡(jiǎn)寫
class Person1 {constructor(public name: string) {this.name = name;};sayName(){console.log(this.name, 2);}
}
存取器與靜態(tài)屬性
-
存取器:TypeScript支持通過getters/setters來截取對(duì)對(duì)象成員的訪問。
-
靜態(tài)屬性:創(chuàng)建類的靜態(tài)成員,這些屬性存在于類本身上面而不是類的實(shí)例上。
let passcode = "secret passcode";class Employee {private _fullName: string;get fullName(): string {return this._fullName;}set fullName(newName: string) {if (passcode && passcode == "secret passcode") {this._fullName = newName;}else {console.log("Error: Unauthorized update of employee!");}}static a = 123;static b (a:number, b: number): number {return a + b ;}
}let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {alert(employee.fullName);
}
抽象類abstract
抽象類做為其它派生類的基類使用。 它們一般不會(huì)直接被實(shí)例化。
存在抽象類、抽象方法
抽象類中有抽象方法,父類中抽象方法不需要實(shí)現(xiàn)(定義),而繼承的子類必須實(shí)現(xiàn)它。
abstract class Animal {abstract makeSound(): void;move(): void {console.log('roaming the earch...');}
}