類常用的語法:
- extends與super
- private姻僧、public、protected、readonly
- get、set
- 抽象類
1.extends與super
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);
}
}
let sam = new Snake("Sammy the Python");
2. private耐薯、public、protected丝里、readonly
class Animal {
public name: string; // 都可以訪問
private age: number;// 類的內(nèi)部可以訪問
protected color: string; // protected的屬性可柿,可以在派生類中訪問
readonly other: string; //只讀屬性
}
- 類的屬性默認是public。
- private屬性不能被聲明的類訪問丙者。
- protected不能類外訪問該屬性,但可以通過實例方法訪問到該屬性营密。
3. get set(通過get械媒、set函數(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!");
}
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
alert(employee.fullName);
}
4. 抽象類
abstract class Department {
constructor(public name: string) {
}
printName(): void {
console.log('Department name: ' + this.name);
}
abstract printMeeting(): void; // 必須在派生類中實現(xiàn)
}
class AccountingDepartment extends Department {
constructor() {
super('Accounting and Auditing'); // 在派生類的構(gòu)造函數(shù)中必須調(diào)用 super()
}
printMeeting(): void {
console.log('The Accounting Department meets each Monday at 10am.');
}
generateReports(): void {
console.log('Generating accounting reports...');
}
}
let department: Department; // 允許創(chuàng)建一個對抽象類型的引用
department = new Department(); // 錯誤: 不能創(chuàng)建一個抽象類的實例
department = new AccountingDepartment(); // 允許對一個抽象子類進行實例化和賦值
department.printName();
department.printMeeting();
department.generateReports(); // 錯誤: 方法在聲明的抽象類中不存在
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者