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 类的基础代码了。

相关推荐
摇滚侠1 小时前
方法 A 等方法 B 执行完再执行 叫同步调用还是异步调用 JS 默认是同步调用还是异步调用
开发语言·javascript·ecmascript
WI8LbH7882 小时前
Ubuntu 部署Harbor
linux·运维·ubuntu
触底反弹2 小时前
🔥 字符串算法面试三连击:反转、回文、回文变种,搞懂这三题稳了!
前端·javascript·算法
触底反弹2 小时前
AI Tool Use 深度解析:大模型是如何"突破物理限制"调用外部工具的?
javascript·人工智能·后端
竹林8182 小时前
从 RPC 超时到批量签名:我用 @solana/web3.js 重构了一个 NFT 铸造页面,踩了这些坑
前端·javascript
橘子星3 小时前
从零手写 RAG 语义检索:基于 Node.js 实现轻量级向量搜索
javascript·人工智能
林希_Rachel_傻希希3 小时前
web性能优化之————图片效果
前端·javascript·面试
橘子星3 小时前
基于 MCP 协议实现本地文件读取工具服务开发实践
javascript·人工智能
Darling噜啦啦3 小时前
前端存储与 this 指向完全指南:从 LocalStorage 实战到 call/apply/bind 深度解析
前端·javascript