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() 创建出来的实例对象。

需要注意:

  • nameage 是实例属性
  • 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:定义类本身的属性或方法
  • publicprivateprotected:控制成员的访问范围
  • extends:实现继承
  • super:在子类中调用父类构造函数

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

相关推荐
To_OC7 小时前
LC 51 N 皇后:我以为难的是回溯,结果栽在了对角线下标
javascript·算法·leetcode
小林ixn8 小时前
从零到一理解 React 父子组件通信:手写一个 Todo 应用带你彻底搞懂单向数据流
前端·javascript·react.js
窝子面11 小时前
手搓最简前后端协作-node
javascript·数据库
kyriewen11 小时前
我让AI给前端项目做了一次完整的Code Review——它和人类的差距,比我想的大得多
前端·javascript·ai编程
এ慕ོ冬℘゜12 小时前
前端基础:什么是时间戳?JS获取时间戳三种方法与实战用途
开发语言·前端·javascript
xqslsm12 小时前
TypeScript 联合类型深入解析
typescript
sugar__salt13 小时前
Vue3 表单双向绑定与响应式核心 API 技术详解
前端·javascript·vue.js
SmartBoyW13 小时前
CSS弹性布局(Flexbox)学习笔记:从零开始搞懂弹性布局
前端·javascript
用户9385156350714 小时前
写了这么久 useState,你真的知道它在干什么吗?
前端·javascript
叫我少年14 小时前
TypeScript 基础类型
typescript