返回

理解Typescript中类的概念和应用

前端

TypeScript系列-类

在面向对象编程中,类是一种抽象的数据类型,它了具有相同特征和行为的一组对象。TypeScript中的类与其他面向对象语言中的类非常相似,它提供了构建和组织代码的结构化方式。

类和对象的创建

要创建一个类,需要使用 class ,后面跟类名,类名通常以大写字母开头。类中可以定义属性和方法,属性是类的成员变量,方法是类的成员函数。

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.`);
  }
}

要创建一个类的实例,可以使用 new 关键字,后面跟类名和实参。

const person1 = new Person('John', 30);
person1.greet(); // Hello, my name is John and I am 30 years old.

类和对象的继承

TypeScript支持类继承,即一个类可以从另一个类继承属性和方法。子类可以覆盖父类的方法,从而实现多态性。

class Employee extends Person {
  salary: number;

  constructor(name: string, age: number, salary: number) {
    super(name, age); // 调用父类的构造函数
    this.salary = salary;
  }

  getSalary() {
    return this.salary;
  }
}

const employee1 = new Employee('Mary', 25, 50000);
employee1.greet(); // Hello, my name is Mary and I am 25 years old.
console.log(`Mary's salary is ${employee1.getSalary()}`); // Mary's salary is 50000

总结

TypeScript中的类提供了构建和组织代码的结构化方式,它支持属性、方法、继承和多态性等面向对象编程的基本原理。通过使用类,可以构建更健壮、可维护的代码。