TypeScript 类的基本使用小结

TypeScript 类的基本使用小结

前言

在 TypeScript 中,class 用来描述一类对象的结构和行为。简单来说,类就像一个"模板",通过这个模板可以创建出多个具有相同属性和方法的对象。

类的核心可以先记住两部分:

  • 属性:描述对象有什么
  • 方法:描述对象能做什么

下面通过一个小例子,把类的基本使用做一个总结。

一、类的基本写法

ts 复制代码
class Person {
  name: string = "张三";
  age: number = 20;

  info(): void {
    console.log(`姓名:${this.name} 年龄:${this.age}`);
  }
}

const person1 = new Person();
person1.info();

这里的 Person 就是一个类,person1 是通过 new Person() 创建出来的实例对象。

需要注意:

  • name 和 age 是实例属性
  • info() 是实例方法
  • this.name 表示访问当前实例对象身上的 name

二、构造函数 constructor

如果希望创建对象时传入不同的数据,可以使用 constructor 构造函数。

ts 复制代码
class Person {
  name: string;
  age: number;

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

  info(): void {
    console.log(`姓名:${this.name} 年龄:${this.age}`);
  }
}

const p1 = new Person("张三", 20);
const p2 = new Person("李四", 18);

p1.info();
p2.info();

构造函数会在创建实例时自动执行,常用来给对象的属性赋初始值。

三、readonly 只读属性

readonly 表示只读属性。它只能在声明时或者构造函数中赋值,后续不能再修改。

ts 复制代码
class Person {
  readonly age: number;

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

const p = new Person(20);
// p.age = 21; // 报错:只读属性不能重新赋值

适合用来保存创建后不希望被随意修改的数据,比如编号、出生日期等。

四、static 静态属性和静态方法

普通属性和方法需要通过实例对象访问,而 static 修饰的内容属于类本身,可以直接通过类名访问。

ts 复制代码
class Person {
  static species: string = "人类";

  static getSpecies(): string {
    return Person.species;
  }
}

console.log(Person.species);
console.log(Person.getSpecies());

静态成员常用于保存和整个类相关的数据或工具方法。

五、访问修饰符

TypeScript 中常见的访问修饰符有三个:

  • public:公开的,类内部和类外部都可以访问,默认就是 public
  • private:私有的,只能在当前类内部访问
  • protected:受保护的,可以在当前类和子类中访问
ts 复制代码
class Person {
  public name: string;
  private idCard: string;
  protected address: string;

  constructor(name: string, idCard: string, address: string) {
    this.name = name;
    this.idCard = idCard;
    this.address = address;
  }
}

访问修饰符的作用是限制属性和方法的使用范围,让代码结构更清晰,也能减少误操作。

六、继承 extends

如果一个类想复用另一个类的属性和方法,可以使用 extends 继承。

ts 复制代码
class Person {
  constructor(public name: string, public age: number) {}

  info(): void {
    console.log(`姓名:${this.name} 年龄:${this.age}`);
  }
}

class Student extends Person {
  constructor(name: string, age: number, public school: string) {
    super(name, age);
  }

  study(): void {
    console.log(`${this.name} 正在 ${this.school} 学习`);
  }
}

const student = new Student("李四", 18, "前端学院");
student.info();
student.study();

在子类构造函数中,需要先调用 super(),它表示调用父类的构造函数。

七、完整示例

ts 复制代码
class Person {
  public name: string;
  readonly age: number;
  static species: string = "人类";
  private idCard: string;
  protected address: string;

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

  info(): void {
    console.log(`姓名:${this.name} 年龄:${this.age}`);
  }

  checkIdCard(): void {
    console.log(`${this.name} 的身份证号已加密保存:${this.idCard.slice(0, 3)}******`);
  }

  static getSpecies(): string {
    return Person.species;
  }
}

class Student extends Person {
  constructor(
    name: string,
    age: number,
    idCard: string,
    address: string,
    public school: string
  ) {
    super(name, age, idCard, address);
  }

  study(): void {
    console.log(`${this.name} 正在 ${this.school} 学习 TypeScript`);
    console.log(`${this.name} 的地址:${this.address}`);
  }
}

const person1 = new Person("张三", 20, "110101200001010011", "北京");
person1.info();
person1.checkIdCard();

console.log(Person.species);
console.log(Person.getSpecies());

const student1 = new Student("李四", 18, "310101200501010022", "上海", "前端学院");
student1.info();
student1.study();

总结

类的基本使用可以按照下面几个关键词来记:

  • class:定义类
  • new:创建实例对象
  • constructor:创建实例时自动执行,用来初始化属性
  • this:指向当前实例对象
  • readonly:定义只读属性
  • static:定义类本身的属性或方法
  • public、private、protected:控制成员的访问范围
  • extends:实现继承
  • super:在子类中调用父类构造函数

掌握这些内容后,就可以读懂和编写大部分 TypeScript 类的基础代码了。

相关推荐
贵沫末8 小时前
Ubuntu——常用软件安装
linux·运维·ubuntu
阿钱真强道11 小时前
15 嵌入式操作系统 | 库的下载、编译、安装与验证(libubox / ubus / uci)
ubuntu·cmake·uci·ubus·libubox
Mr_Mao13 小时前
告别选型困难!集 VueUse、ahooks、Mantine 于一身:286 个 Hook 的 ReaUse 来了
前端·javascript·react.js
云杂项13 小时前
tmux指南:安装、配置与高效使用(Ubuntu上)
linux·服务器·ubuntu
艸肅13 小时前
Ubuntu 安装 JDK (含手动安装)
java·ubuntu·jdk
默_笙14 小时前
🚙 一条腿走路会摔:ES 关键词检索、混合召回与 ReRank 裁判
前端·javascript
dsyyyyy110114 小时前
Vue 3 Watch 监视完全指南
前端·javascript·vue.js
u01110267516 小时前
Vue 3 实现图片裁剪框:拖动、缩放与固定宽高比
前端·javascript·vue.js
0nirvana017 小时前
从普通 script 到 ESM:一文搞懂 JavaScript 模块、IIFE 和 window
javascript
zhangrelay18 小时前
ROS2 Lyrical实验5导航Nav2
linux·笔记·学习·ubuntu·机器人