使用类实现功能
ts中类的继承
ES6中class类中,属性分为:实例上的属性,原型上的方法;也可以叫做:class的属性,class的方法。
类的继承叫法:父类=>子类,基类=>派生类;它们本质上是一样的。
super指向父类的构造函数
继承简单功能:扩展现有的类,通过抽离父类的方式来实现子类的复用。(实现公共方法的抽离,让子类实现复用)。
类上注解实例上的属性:
class Greeter {
greeting: number; //仅当类被实例化的时候才会被初始化的属性
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 | 自身、子类、实例 |
private | 自身 |
protected | 自身和子类 |
readonly | 只读属性必须在声明时或构造函数里被初始化。 |
readonly只会用在属性签名或者索引签名(签名是数字)前面。
简写问题:
类中属性不写修饰符,默认被public修饰。
class Person {
public name: string;
constructor(theName: string) {
this.name = theName;
};
sayName(){
console.log(this.name, 2);
}
}
// 简写
class Person1 {
constructor(public name: string) {
this.name = name;
};
sayName(){
console.log(this.name, 2);
}
}
存取器与静态属性
-
存取器:TypeScript支持通过getters/setters来截取对对象成员的访问。
-
静态属性:创建类的静态成员,这些属性存在于类本身上面而不是类的实例上。
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
抽象类做为其它派生类的基类使用。 它们一般不会直接被实例化。
存在抽象类、抽象方法
抽象类中有抽象方法,父类中抽象方法不需要实现(定义),而继承的子类必须实现它。
abstract class Animal {
abstract makeSound(): void;
move(): void {
console.log('roaming the earch...');
}
}