类描述了所创建的对象共同的属性和方法。
class Dog {
constructor(name: string) {
this.name = name;
}
name: string = ‘dog‘;
}
let dog = new Dog(‘hello‘);
console.log(dog);
TypeScript 支持继承类,即我们可以在创建类的时候继承一个已存在的类,这个已存在的类称为父类,继承它的类称为子类。
类继承使用关键字 extends,子类除了不能继承父类的私有成员(方法和属性)和构造函数,其他的都可以继承。
TypeScript 一次只能继承一个类,不支持继承多个类,但 TypeScript 支持多重继承(A 继承 B,B 继承 C)。
class Dog {
constructor(name: string) {
this.name = name;
}
name: string = ‘dog‘;
}
class Husky extends Dog {
constructor(name: string, color: string) {
super(name);
this.color = color;
}
color: string = ‘blue‘;
}
let dog = new Dog(‘hello‘);
console.log(dog);
类的修饰符有public, private, protected, readonly, static,下面我们来看看分别代表什么含义。
public: public 修饰的属性或方法是公有的,可以在任何地方被访问到,默认所有的属性和方法都是 public 的
private: private 私有成员,不能被实例调用,也不能被子类调用, 也可以在构造函数中加上private
protected: protected 受保护成员 protected只能在类,或者子类中访问,而不能被实例访问。也就是这个方法或者属于不能被实例,只能被继承,也就是一个基类。
readonly: 只读属性,只读属性需要被初始化。
static: 类的静态成员,只能通过类的父类来调用,而不能通过子类来调用。
class Dog {
constructor(name: string) {
this.name = name;
}
name: string = ‘dog‘;
readonly legs:number = 4; // 只读属性需要加上默认值
static food:string = ‘bones‘;
private priv() {}
protected pro() {}
}
class Husky extends Dog {
constructor(name: string, color: string) {
super(name);
this.color = color;
this.pro(); // 这里是protected
// this.pri(); // pri在类的Husky中不存在
}
color: string = ‘blue‘;
}
let dog = new Dog(‘hello‘);
// console.log(dog.priv()); // 这里会报private是私有属性,只能在Dog中使用
// console.log(dog.food); // 属性“food”在类型“Dog”上不存在。你的意思是改为访问静态成员“Dog.food”吗?
console.log(Dog.food);
原文:https://www.cnblogs.com/Joannamo/p/14503415.html