09.TypeScript Class类

09.TypeScript Class类

1. 类的基本概念

在TypeScript中,类(Class)是一种面向对象编程的核心概念,它定义了对象的属性和方法。类可以看作是创建对象的模板或蓝图。

2. 类的定义

使用 class 关键字来定义一个类。类可以包含属性、构造函数和方法。

typescript 复制代码
// 定义一个简单的类
class Person {
  // 属性
  name: string;
  age: number;
  
  // 构造函数
  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
  
  // 方法
  greet() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

// 创建类的实例
const person1 = new Person("Alice", 25);
person1.greet(); // 输出: Hello, my name is Alice and I am 25 years old.

3. 类的继承

TypeScript支持类的继承,子类可以继承父类的属性和方法,并可以添加自己的属性和方法。使用 extends 关键字来实现继承。

typescript 复制代码
// 父类
class Animal {
  name: string;
  
  constructor(name: string) {
    this.name = name;
  }
  
  move(distance: number = 0) {
    console.log(`${this.name} moved ${distance} meters.`);
  }
}

// 子类
class Dog extends Animal {
  breed: string;
  
  constructor(name: string, breed: string) {
    super(name); // 调用父类的构造函数
    this.breed = breed;
  }
  
  bark() {
    console.log("Woof! Woof!");
  }
}

// 创建子类的实例
const dog1 = new Dog("Rufus", "Golden Retriever");
dog1.move(10); // 输出: Rufus moved 10 meters.
dog1.bark(); // 输出: Woof! Woof!

4. 访问修饰符

TypeScript提供了三种访问修饰符:publicprivateprotected

  • public:默认的访问修饰符,可以在任何地方访问。
  • private:只能在类的内部访问。
  • protected:可以在类的内部和子类中访问。
typescript 复制代码
class Car {
  public brand: string; // 公共属性
  private model: string; // 私有属性
  protected year: number; // 受保护的属性
  
  constructor(brand: string, model: string, year: number) {
    this.brand = brand;
    this.model = model;
    this.year = year;
  }
  
  public getCarInfo() {
    // 在类的内部可以访问所有属性
    return `${this.brand} ${this.model} (${this.year})`;
  }
  
  private getEngineInfo() {
    // 私有方法,只能在类的内部访问
    return "V8 Engine";
  }
  
  protected getMaintenanceInfo() {
    // 受保护的方法,可以在类的内部和子类中访问
    return "Regular maintenance required";
  }
}

const car1 = new Car("Toyota", "Camry", 2020);
console.log(car1.brand); // 输出: Toyota
// console.log(car1.model); // 错误:无法访问私有属性
// console.log(car1.year); // 错误:无法访问受保护的属性
console.log(car1.getCarInfo()); // 输出: Toyota Camry (2020)
// car1.getEngineInfo(); // 错误:无法访问私有方法
// car1.getMaintenanceInfo(); // 错误:无法访问受保护的方法

5. 子类中访问修饰符的使用

typescript 复制代码
class ElectricCar extends Car {
  private batteryCapacity: number;
  
  constructor(brand: string, model: string, year: number, batteryCapacity: number) {
    super(brand, model, year);
    this.batteryCapacity = batteryCapacity;
  }
  
  public getElectricCarInfo() {
    // 在子类中可以访问父类的公共属性和受保护的属性
    return `${this.brand} ${this.model} (${this.year}) - Battery: ${this.batteryCapacity}kWh`;
  }
  
  protected getMaintenanceInfo() {
    // 重写父类的受保护方法
    return "Regular maintenance and battery check required";
  }
  
  public getMaintenanceDetails() {
    // 在子类中可以访问受保护的方法
    return this.getMaintenanceInfo();
  }
}

const electricCar1 = new ElectricCar("Tesla", "Model S", 2022, 100);
console.log(electricCar1.getElectricCarInfo()); // 输出: Tesla Model S (2022) - Battery: 100kWh
console.log(electricCar1.getMaintenanceDetails()); // 输出: Regular maintenance and battery check required
// console.log(electricCar1.batteryCapacity); // 错误:无法访问私有属性

6. 静态属性和方法

使用 static 关键字可以定义类的静态属性和方法,它们属于类本身,而不是类的实例。

typescript 复制代码
class MathUtils {
  static PI: number = 3.14159;
  
  static calculateCircleArea(radius: number): number {
    return MathUtils.PI * radius * radius;
  }
}

console.log(MathUtils.PI); // 输出: 3.14159
console.log(MathUtils.calculateCircleArea(5)); // 输出: 78.53975

// 无法通过实例访问静态属性和方法
// const utils = new MathUtils();
// console.log(utils.PI); // 错误
// console.log(utils.calculateCircleArea(5)); // 错误

7. 抽象类

使用 abstract 关键字可以定义抽象类。抽象类不能被实例化,只能被继承。抽象类可以包含抽象方法,这些方法必须在子类中实现。

typescript 复制代码
abstract class Shape {
  abstract getArea(): number; // 抽象方法
  
  toString(): string {
    return `Area: ${this.getArea()}`;
  }
}

class Rectangle extends Shape {
  width: number;
  height: number;
  
  constructor(width: number, height: number) {
    super();
    this.width = width;
    this.height = height;
  }
  
  getArea(): number {
    return this.width * this.height;
  }
}

const rectangle = new Rectangle(5, 3);
console.log(rectangle.toString()); // 输出: Area: 15

// 无法实例化抽象类
// const shape = new Shape(); // 错误

8. 总结

  1. 类的定义 :使用 class 关键字定义类,类可以包含属性、构造函数和方法。
  2. 类的实例化 :使用 new 关键字创建类的实例。
  3. 类的继承 :使用 extends 关键字实现类的继承,子类可以继承父类的属性和方法。
  4. 访问修饰符publicprivateprotected 控制属性和方法的访问权限。
  5. 静态属性和方法 :使用 static 关键字定义属于类本身的属性和方法。
  6. 抽象类 :使用 abstract 关键字定义抽象类,抽象类不能被实例化,只能被继承。
  7. 构造函数 :使用 constructor 定义类的构造函数,在创建实例时初始化属性。
  8. 方法重写:子类可以重写父类的方法,提供不同的实现。
相关推荐
weixin_382395234 小时前
为小工厂量身打造:本地部署的物料管理系统带缺料计算
前端·制造
__zRainy__5 小时前
解决pnpm v10+不自动构建
前端·pnpm·工程化
猫猫不是喵喵.5 小时前
Vue3 Props 属性
前端·javascript·vue.js
醉城夜风~6 小时前
CSS元素显示模式(display)
前端·css
AI大模型-小华7 小时前
Codex 三方充值快速入门指南
java·前端·数据库·chatgpt·ai编程·codex·chatgpt pro
做前端的娜娜子9 小时前
同一链接实现 PC Web 与移动 H5 自适应
前端·掘金·金石计划
小帅不太帅9 小时前
架构没变、规模没变,DeepSeek V4 Flash 正式版凭什么暴涨 47 分?
前端·aigc·deepseek
jarvisuni10 小时前
DeepSeekFlash前端依旧拉垮,而且变慢了很多!
前端·javascript·算法
卷福同学11 小时前
AI编程出海第二步:验证关键词能否做站
前端·人工智能·后端