当前位置: 首页 > ops >正文

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 方法。
  • CircleRectangle 是子类,重写了 getArea 方法,实现不同的面积计算。
  • 通过多态,shapes 数组中的每个对象调用 getArea 方法时,会根据实际类型执行相应的实现。

4. thissuper

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 属性。
  • Childgreet 方法中,使用 super.greet() 调用父类的 greet 方法,然后输出年龄信息。

5. 综合案例

以下是一个综合案例,展示了继承、单继承、函数覆盖、多态、thissuper 的使用。

// 父类: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 是父类,包含 nameage 属性,以及 introduce 方法。
  • Employee 是子类,继承自 Person,并添加了 employeeIdsalary 属性,以及 work 方法。
  • ManagerEmployee 的子类,添加了 department 属性,并重写了 introduce 方法。
  • introduce 方法中,使用 super.introduce() 调用父类的 introduce 方法,实现方法扩展。
  • 通过多态,employees 数组中的每个对象调用 introduce 方法时,会根据实际类型执行相应的实现。
  • 使用 instanceof 判断对象的实际类型,并调用相应的方法。

总结

通过以上内容,我们全面了解了 TypeScript 中的继承机制,包括继承语法、单继承、函数覆盖与多态,以及 thissuper 的使用。继承是面向对象编程的重要特性,能够帮助开发者构建结构清晰、可复用的代码结构。

http://www.xdnf.cn/news/7511.html

相关文章:

  • Kotlin 协程 (三)
  • vivado fpga程序固化
  • 学习黑客数据小包的TLS冒险之旅
  • Java 07异常
  • 将 Workbook 输出流直接上传到云盘
  • Apollo10.0学习——planning模块(8)之Frame类
  • 使用VGG-16模型来对海贼王中的角色进行图像分类分类
  • python打卡day31
  • SQLynx 团队协作实践:提升数据库开发效率的解决方案​
  • 4-5月份,思科,华为,微软,个别考试战报分享
  • Axure中使用动态面板实现图标拖动交换位置
  • C++23 新增扁平化关联容器详解
  • 微小店推客系统开发:构建全民营销矩阵,解锁流量增长密码
  • Java EE进阶1:导读
  • Spring Cloud Gateway深度解析:原理、架构与生产实践
  • 根据当前日期计算并选取上一个月和上一个季度的日期范围,用于日期控件的快捷选取功能
  • MySQL 8.0 OCP 英文题库解析(七)
  • 在 Git 中添加子模块(submodule)的详细步骤
  • kotlin 将一个list按条件分为两个list(partition )
  • 漏洞检测与渗透检验在功能及范围上究竟有何显著差异?
  • iOS Runtime与RunLoop的对比和使用
  • 基于flask+vue的电影可视化与智能推荐系统
  • PostgreSQL架构
  • HTML应用指南:利用POST请求获取全国申通快递服务网点位置信息
  • 华为云鲲鹏型kC2云服务器——鲲鹏920芯片性能测评
  • 【EI会议火热征稿中】第二届云计算与大数据国际学术会议(ICCBD 2025)
  • 程序运行报错分析文档
  • 使用 adb 命令截取 Android 设备的屏幕截图
  • CentOS 7连接公司网络配置指南
  • BERT 作为Transformer的Encoder 为什么采用可学习的位置编码