public
修饰符(谁都可以访问到)class Animal { public name: string; // 不写public默认也是公开的 public age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } } class Cat extends Animal { constructor(name: string, age: number) { super(name, age); console.log(this.name, this.age); // 子类访问 } } let p = new Cat('Bai', 18); console.log(p.name, p.age); // 外层访问
protected
修饰符 (自己和子类可以访问到)class Animal { constructor(protected name: string, protected age: number) { this.name = name; this.age = age; } } class Cat extends Animal { constructor(name: string, age: number) { super(name, age); console.log(this.name, this.age) // 子类中可以访问 } } let p = new Cat('Bai', 18); console.log(p.name,p.age);// 外部无法访问
private
修饰符 (除了自己都访问不到)class Animal { constructor(private name: string, private age: number) { this.name = name; this.age = age; console.log(this.name, this.age); // 自身可以访问 } } class Cat extends Animal { constructor(name: string, age: number) { super(name, age); console.log(this.name, this.age); // 无法访问 } } let p = new Cat('Bai', 18); console.log(p.name, p.age); // 无法访问
readonly
修饰符 (只能读取该值)class Animal { constructor(public readonly name: string, public age: number) { this.name = name; this.age = age; } changeName(name: string) { this.name = name; // 无法成功赋值,仅读属性只能在constructor中被赋值 } }
3.静态属性和方法
class Animal { static type = '哺乳动物'; // 静态属性 static getName() { // 静态方法 return '动物类'; } } let animal = new Animal(); console.log(Animal.type, Animal.getName());
4.super
class Animal { static getType() { return '动物'; } say(message: string) { console.log(message); } } class Cat extends Animal { static getType() { // 静态方法中的super指代的是父类 return super.getType(); } say() { // 原型方法中的super指代的是父类的原型 super.say('猫猫叫'); } } let cat = new Cat(); console.log(Cat.getType(), cat.say());
5.抽象类
抽象类无法被实例化,只能被继承,抽象方法不能在抽象类中实现,只能在抽象类的具体子类中实现,而且必须实现。
abstract class Animal{ name!:string; abstract speak():void } class Cat extends Animal { speak(){ console.log('猫猫叫'); } }
来源:https://www.cnblogs.com/zhengrongbaba/p/15045385.html