在 TypeScript 中,类是一种用于创建对象的蓝图或模板。类定义了对象的属性和方法。它是一种面向对象编程的概念,用于组织和封装相关的数据和功能。

下面是一些常见的类的示例:

  1. 基本类:这是最简单的类形式,只包含属性和方法的定义。
class Person {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  sayHello() {
    console.log('Hello, my name is ' + this.name + ' and I'm ' + this.age + ' years old.');
  }
}
  1. 继承:通过继承可以创建一个类从另一个类派生出来,继承了父类的属性和方法。
class Student extends Person {
  grade: string;

  constructor(name: string, age: number, grade: string) {
    super(name, age);
    this.grade = grade;
  }

  study() {
    console.log(this.name + ' is studying in grade ' + this.grade + '.');
  }
}
  1. 访问修饰符:通过访问修饰符可以控制类成员的访问权限,包括 public(默认)、private 和 protected。
class Car {
  private brand: string;
  protected color: string;

  constructor(brand: string, color: string) {
    this.brand = brand;
    this.color = color;
  }

  protected honk() {
    console.log('The ' + this.color + ' ' + this.brand + ' is honking.');
  }
}

class SportsCar extends Car {
  constructor(brand: string, color: string) {
    super(brand, color);
  }

  startEngine() {
    console.log('The ' + this.color + ' ' + this.brand + ' is starting the engine.');
    this.honk(); // 可以访问父类的 protected 方法
  }
}

这些只是一些基本的类示例,类还可以包含静态属性和方法、抽象类、接口等。

TypeScript 类详解:概念、示例和应用

原文地址: https://www.cveoy.top/t/topic/qlzl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录