文章目录
TypeScript类基本使用的补充
抽象类的使用
我们知道,继承是多态使用的前提。
什么是抽象方法? 在TypeScript中没有具体实现的方法(没有方法体),就是抽象方法。
我们来看下面这样一个例子
function makeArea(shape: Shape) {
return shape.getArea()
}
// 定义抽象父类
abstract class Shape {
// 定义抽象方法
abstract getArea(): number
}
// 1.定义计算矩形面积的类
class Rectangle extends Shape {
width: number
height: number
constructor(width: number, height: number) {
super()
this.width = width
this.height = height
}
getArea() {
return this.width * this.height
}
}
// 2.定义计算圆形面积的类
class Circle extends Shape {
r: number
constructor(r: number) {
super()
this.r = r
}
getArea() {
return this.r * this.r * 3.14
}
}
// 测试
const reactangle = new Rectangle(10, 20)
const circle = new Circle(2)
console.log(makeArea(reactangle))
console.log(makeArea(circle))
抽象类有如下的特点:
类的类型
类本身也是可以作为一种数据类型的:
- 例如下面代码中, 此时p就是Person类型的
class Person {
name: string = "aaa"
eating() {
console.log("eating")
}
}
const p = new Person()
- 我们也可以字面量的方式创建一个变量p, 要求他是Person类型的, 那么我们要保证对应的属性和方法需要与Person保持一致
class Person {
name: string = "aaa"
eating() {
console.log("eating")
}
}
const p: Person = {
// 属性需要和Person类保持一致
name: "chenyq",
eating() {
console.log("p eating")
}
}
应用场景
- 我们可以传入Person类的实例对象
class Person {
name: string
constructor(name: string) {
this.name = name
}
}
function printName(p: Person) {
console.log(p.name)
}
// 测试
const p1 = new Person("chenyq")
const p2 = new Person("kaisa")
printName(p1)
printName(p2)
- 也可以传入和Person类属性和方法能够一一对应的对象
class Person {
name: string
eating() {
console.log("eating")
}
constructor(name: string) {
this.name = name
}
}
function printName(p: Person) {
console.log(p.name)
}
// 测试
printName({ name: "kaisa", eating() {} })