侧重于对象的编程,扩展性强,成本低,当程序出问题后定位对象即可,哪个对象出问题就找哪个对象修复就可以。
类与对象
通过对象表示具体的实物,对象是通过类创建的,对象能干什么完全取决于类如何定义。
class Vehicle {
// 属性(特性)
color: "白色"; // 颜色
maxSpeed: 220; // 最高速度
// 方法(能力)
drive() {
console.log("run"); // 驾驶
};
honk() {
console.log("didi"); // 鸣笛
};
};
// 创建实例对象
const vehicle = new Vehicle("红色", 240);
Vehicle.drive(); // 调用对象的方法
构造函数
用来在创建对象时为对象属性赋初始值,在使用 new 关键字实例化对象时被自动调用。
在TypeScript
中构造函数使用constructor
实现,在该方法中通过this
关键字访问当前类中的属性和方法。
class Vehicle {
// 属性(特性)
color: "白色"; // 颜色
maxSpeed: 220; // 速度
// 方法(能力)
drive() { // 驾驶
console.log("run");
};
honk() { // 鸣笛
console.log("didi");
};
// 构造函数:用于创建对象时初始化参数的值。
construction(color: string, maxSpeed: number) {
this.color = color;
this.maxSpeed = maxSpeed;
};
};
// 创建实例对象
const vehicle = new Vehicle("红色", 240);
只读属性
在属性前加上
readonly
关键字,用于修饰只读属性。
只读属性是指一旦被赋值,该值就不能修改,无论在类的外部还是内部都不能修改。
class Vehicle {
// 已有初始值
readonly maxSpeed = 240; // 只读:最高速度
construction() {
// this.maxSpeed = 300; // 会报错,无法修改只读属性。
};
drive() {
// this.maxSpeed = 2000; // 会报错,无法修改只读属性。
};
}
继承
子类继承父类后,可以通过重写父类方法对功能进行扩展。
- 重载的方法前面要加上
override
。
// 父类
class Vehicle {
wheels: number = 4;
};
// 子类
class Car extends Vehicle {
brand: string = "BMW";
};
// 创建汽车实例
const car = new Car(); // { wheels: 4, brand: "BWM }
super 关键字
用于接收子类传递给父类的参数。
// 父类
class Vehicle {
wheels: number; // 轮子数量
constructor(wheels: number) {
this.wheels = wheels;
};
};
// 子类
class Car extends Vehicle {
brand: string; // 品牌
constructor(brand: string, wheels: number) {
// 父类属性初始化
super(wheels);
// 子类属性初始化
this.brand = brand;
};
};
// 创建汽车实例
const car1 = new Car("BWM", 4); // { wheels: 4, brand: "BWM" }
const car2 = new Car("BYD", 8); // { wheels: 8, brand: "BYD" }
重写父类方法
通过
override
关键字重写父类方法。
可以通过super
重新去调用父类的方法。
// 父类
class Vehicle {
wheels: number; // 轮子数量
constructor(wheels: number) {
this.wheels = wheels;
};
drive() {
console.log("父类drive方法");
};
};
// 子类
class Car extends Vehicle {
brand: string; // 品牌
constructor(brand: string, wheels: number) {
// 父类属性初始化
super(wheels);
// 子类属性初始化
this.brand = brand;
};
override drive() {
console.log("子类重写的drive方法");
// 也可以通过super重新调用父类的drive方法
super.drive();
};
};
// 创建汽车实例
const car1 = new Car("BWM", 4); // { wheels: 4, brand: "BWM" }
const car2 = new Car("BYD", 8); // { wheels: 8, brand: "BYD" }
抽象类
抽象类因继承而存在,通过抽象类可以约束子类必须实现哪些成员,如果抽象类不被继承,它将毫无意义。抽象类通过
abstract
修饰。
在抽象类中可以只定义成员,具体的成员实现由子类完成并且必须完成,所以抽象类不能被直接实例化。
// 抽象类
abstract class Shape {
abstract color: string;
abstract render(): void;
};
// 继承抽象类必须实现属性和方法
class Circle extends Shape {
color: string = "skyblue";
render(): void {
console.log("render");
};
};
// 抽象类不能实例化,必须被继承
// new Shape();