1.修饰符
public 公有 父类(自身)以及子类和外部都能访问
protected 受保护 父类(自身)以及子类都能访问 但是外部不能访问
private 私有的 父类(自身)可以访问 但是子类和外部不能访问
2.基本使用
class Person {
// name: string;
static age: number = 18; // 静态属性
// constructor(name: string) {
// this.name = name;
// }
// 上面两个的合并 是一种缩写
constructor(protected name: string) {
this.name = name;
}
run(): void {
console.log(this.name + "正在运动");
console.log(Person.age); //这里是可以用静态变量的
}
// 类里面的方法,有返回值 [propName:string]: any表示不定参数
getInfo(): { id: string, name: string, [propName:string]: any } {
return {
age1: 18,
age: 18,
id: "1",
name: this.name,
};
}
// 类里面的方法,无返回值
printName(profix: string): void {
console.log(profix + ":" + this.name);
}
// getter
get myName() {
return this.name;
}
// setter
set myName(newVal) {
this.name = newVal;
}
// 静态方法
static getStaticInfo(): void {
Person.age = 20;
// 静态方法里不能用非静态变量 如 上面的name,只能用静态变量
console.log(Person.age);
}
}
let p = new Person("战三");
p.run(); // 战三正在运动 18
console.log(p.getInfo()); // {name:"战三"}
Person.getStaticInfo(); //20
// console.log(p.name) // 因为是protected,所以外部不能访问 这里会报错
3.继承
// 继承
class Child extends Person {
public count: number;
constructor(name: string, count: number) {
super(name); //子类继承 要实现super
this.count = count;
}
// 多态 重写父级方法
printName(profixChild: string): void {
console.log(profixChild + ":" + this.name + "child"); // 因为是protected,所以子集能访问,如果是private,就会报错
}
}
let c = new Child("子集", 20);
4.抽象类(可以规定类的一些标准)
// 抽象类 (可以规定类的一些标准)
abstract class People1 {
age: number;
constructor(age: number) {
this.age = age;
}
printAge() {
console.log(this.age);
}
abstract name: string; // 抽象属性 必须子类实现
abstract getName(): string; // 抽象方法,必须子类实现
}
class Man extends People1 {
public name: string; // 实现抽象属性
constructor(age: number, name: string) {
super(age);
this.name = name;
}
// 实现抽象方法
getName(): string {
return this.name + "Child";
}
}
let mm = new Man(18, "张三");
mm.printAge();
console.log(mm.getName());