Typescript学习教程,从入门到精通,TypeScript 继承语法知识点及案例代码(8)
TypeScript 继承语法知识点及案例代码
TypeScript 作为 JavaScript 的超集,提供了面向对象编程(OOP)的特性,其中继承(Inheritance)是核心概念之一。通过继承,可以创建一个类(子类)来复用另一个类(父类)的属性和方法,从而实现代码的复用和扩展。
1. 继承语法
在 TypeScript 中,使用 extends
关键字实现继承。子类可以继承父类的属性和方法,并可以添加新的属性和方法或重写(覆盖)父类的方法。
基本语法
class 父类 {// 父类的属性和方法
}class 子类 extends 父类 {// 子类的属性和方法
}
示例
class Animal {name: string;constructor(name: string) {this.name = name;}makeSound(): void {console.log("Animal makes a sound");}
}class Dog extends Animal {breed: string;constructor(name: string, breed: string) {super(name); // 调用父类的构造函数this.breed = breed;}makeSound(): void {console.log("Woof! Woof!");}fetch(): void {console.log(`${this.name} is fetching the ball.`);}
}// 使用
const myDog = new Dog("Buddy", "Golden Retriever");
myDog.makeSound(); // 输出: Woof! Woof!
myDog.fetch(); // 输出: Buddy is fetching the ball.
解释:
Animal
是父类,包含name
属性和makeSound
方法。Dog
是子类,继承自Animal
,并添加了breed
属性和fetch
方法。- 在子类的构造函数中,使用
super(name)
调用父类的构造函数来初始化name
属性。 - 子类重写了
makeSound
方法,实现多态。
2. 单继承
TypeScript 支持单继承,即一个子类只能继承一个父类。这与某些其他语言(如 C++ 支持多继承)不同。
示例
class Vehicle {wheels: number;constructor(wheels: number) {this.wheels = wheels;}start(): void {console.log("Vehicle started.");}
}class Car extends Vehicle {doors: number;constructor(wheels: number, doors: number) {super(wheels);this.doors = doors;}start(): void {console.log("Car started with ignition.");}openDoors(): void {console.log(`Car with ${this.doors} doors opened.`);}
}// 使用
const myCar = new Car(4, 4);
myCar.start(); // 输出: Car started with ignition.
myCar.openDoors(); // 输出: Car with 4 doors opened.
解释:
Vehicle
是父类,包含wheels
属性和start
方法。Car
是子类,继承自Vehicle
,并添加了doors
属性和openDoors
方法。Car
重写了start
方法,实现了方法覆盖。
3. 函数覆盖与多态
函数覆盖(Method Overriding)是指子类重写父类的方法。多态(Polymorphism)是指同一个方法在不同类中有不同的实现。
示例
class Shape {name: string;constructor(name: string) {this.name = name;}getArea(): number {return 0;}
}class Circle extends Shape {radius: number;constructor(radius: number) {super("Circle");this.radius = radius;}getArea(): number {return Math.PI * this.radius ** 2;}
}class Rectangle extends Shape {width: number;height: number;constructor(width: number, height: number) {super("Rectangle");this.width = width;this.height = height;}getArea(): number {return this.width * this.height;}
}// 使用
const shapes: Shape[] = [new Circle(5), new Rectangle(4, 6)];shapes.forEach(shape => {console.log(`${shape.name} area: ${shape.getArea()}`);
});
输出:
Circle area: 78.53981633974483
Rectangle area: 24
解释:
Shape
是父类,包含name
属性和getArea
方法。Circle
和Rectangle
是子类,重写了getArea
方法,实现不同的面积计算。- 通过多态,
shapes
数组中的每个对象调用getArea
方法时,会根据实际类型执行相应的实现。
4. this
与 super
this
this
关键字指向当前对象的实例。在子类的方法中,this
可以访问子类的属性和方法。
super
super
关键字用于调用父类的构造函数和方法。
示例
class Parent {name: string;constructor(name: string) {this.name = name;}greet(): void {console.log(`Hello, my name is ${this.name}.`);}
}class Child extends Parent {age: number;constructor(name: string, age: number) {super(name); // 调用父类的构造函数this.age = age;}greet(): void {// 使用 super 调用父类的方法super.greet();console.log(`And I am ${this.age} years old.`);}
}// 使用
const child = new Child("Alice", 8);
child.greet();
输出:
Hello, my name is Alice.
And I am 8 years old.
解释:
Parent
是父类,包含name
属性和greet
方法。Child
是子类,继承自Parent
,并添加了age
属性。- 在
Child
的构造函数中,使用super(name)
调用父类的构造函数来初始化name
属性。 - 在
Child
的greet
方法中,使用super.greet()
调用父类的greet
方法,然后输出年龄信息。
5. 综合案例
以下是一个综合案例,展示了继承、单继承、函数覆盖、多态、this
和 super
的使用。
// 父类:Person
class Person {name: string;age: number;constructor(name: string, age: number) {this.name = name;this.age = age;}introduce(): void {console.log(`Hi, I am ${this.name} and I am ${this.age} years old.`);}
}// 子类:Employee
class Employee extends Person {employeeId: number;salary: number;constructor(name: string, age: number, employeeId: number, salary: number) {super(name, age); // 调用父类构造函数this.employeeId = employeeId;this.salary = salary;}// 重写 introduce 方法introduce(): void {super.introduce();console.log(`I am an employee with ID ${this.employeeId} and my salary is ${this.salary}.`);}// 新方法work(): void {console.log(`${this.name} is working.`);}
}// 子类:Manager
class Manager extends Employee {department: string;constructor(name: string, age: number, employeeId: number, salary: number, department: string) {super(name, age, employeeId, salary);this.department = department;}// 重写 introduce 方法introduce(): void {super.introduce();console.log(`I am the manager of ${this.department} department.`);}// 新方法manage(): void {console.log(`${this.name} is managing ${this.department} department.`);}
}// 使用
const employees: Person[] = [new Employee("Bob", 30, 101, 5000),new Manager("Carol", 40, 102, 8000, "Sales")
];employees.forEach(person => {person.introduce();if (person instanceof Employee) {(person as Employee).work();}if (person instanceof Manager) {(person as Manager).manage();}console.log("---");
});
输出:
Hi, I am Bob and I am 30 years old.
I am an employee with ID 101 and my salary is 5000.
Bob is working.
---
Hi, I am Carol and I am 40 years old.
I am an employee with ID 102 and my salary is 8000.
I am the manager of Sales department.
Carol is managing Sales department.
---
解释:
Person
是父类,包含name
和age
属性,以及introduce
方法。Employee
是子类,继承自Person
,并添加了employeeId
和salary
属性,以及work
方法。Manager
是Employee
的子类,添加了department
属性,并重写了introduce
方法。- 在
introduce
方法中,使用super.introduce()
调用父类的introduce
方法,实现方法扩展。 - 通过多态,
employees
数组中的每个对象调用introduce
方法时,会根据实际类型执行相应的实现。 - 使用
instanceof
判断对象的实际类型,并调用相应的方法。
总结
通过以上内容,我们全面了解了 TypeScript 中的继承机制,包括继承语法、单继承、函数覆盖与多态,以及 this
和 super
的使用。继承是面向对象编程的重要特性,能够帮助开发者构建结构清晰、可复用的代码结构。