TypeScript 系列 -- Class 类的语法和继承

Class 类的基础语法

创建类

class关键字加"类名"即可

ts 复制代码
class Player {
}

定义属性

属性一般写在类里面的顶部

ts 复制代码
class Player {
  // 定义属性
  name: string;
  health: number;
  damage: number;
}

constructor 方法

constructor 方法用于给实例的属性赋值,并设定默认值

constructor 接收一个参数 props,类型为 PlayerProps,逐个从 props 中取出各属性,并用 ??||的升级版,保留了''0false)后面加默认值
注意 this 的指向:class 类里的 this 指向用此类 new 生成的实例

所以 this.name = props.name ?? 'Unknown' 就是在给实例的属性赋初值的过程

ts 复制代码
interface PlayerProps {
  name?: string; // 名称
  health?: number; // 血量
  damage?: number; // 伤害值
}

class Player {
  // 定义属性
  name: string;
  health: number;
  damage: number;
  
  // 为属性赋值(并规定好默认值)
  constructor(props: PlayerProps) {
    this.name = props.name ?? 'Unknown';
    this.health = props.health ?? 0;
    this.damage = props.damage ?? 0;
  }
}

定义方法

ts 复制代码
interface PlayerProps {
  name?: string; // 名称
  health?: number; // 血量
  damage?: number; // 伤害值
}

class Player {
  // 定义属性
  name: string;
  health: number;
  damage: number;
  
  // 为属性赋值(并规定好默认值)
  constructor(props: PlayerProps) {
    this.name = props.name ?? 'Unknown';
    this.health = props.health ?? 0;
    this.damage = props.damage ?? 0;
  }
  
  // 定义方法
  move(direction: 'left' | 'right') {
    console.log(`${this.name}向${direction}移动`);
  }
  recover(bloodVolume: number) {
    console.log(`${this.name}恢复血量:+${bloodVolume}`);
    this.health += bloodVolume;
  }
}

自此,一个 Player 类已创建完成

创建实例并测试

ts 复制代码
const player1 = new Player({
  name: 'PlayerA',
  health: 100,
  damage: 20
);
console.log(player1.name); // PlayerA
console.log(player1.health); // 100
console.log(player1.damage); // 20
player1.move('left'); // PlayerA向left移动
player1.recover(10); // PlayerA恢复血量:+10

Class 类的继承

想要实现这样的继承关系:

  • 玩家Player是基类,战士Warrior和射手Shooter是子类,都继承自Player基类
  • 基类Player通用属性:名称、血量、伤害值;通用方法:移动、恢复生命
  • 子类Warrior独有属性:防御伤害值;独有方法:开启盾牌防御
  • 子类Shooter独有属性:射程;独有方法:射击

定义基类和子类的属性类型

  • extends 表示"继承自"
  • WarriorProps既包含PlayerProps的所有属性,又包含自己的属性defense
ts 复制代码
interface PlayerProps {
  name?: string; // 玩家通用属性:名称
  health?: number; // 玩家通用属性:血量
  damage?: number; // 玩家通用属性:伤害值
}
interface WarriorProps extends PlayerProps {
  defense?: number; // 战士独有属性:防御伤害值
}
interface ShooterProps extends PlayerProps {
  shootRange?: number; // 射手独有属性:射程
}

子类继承自基类

  • extends 表示"继承自"
  • super 表示"父类的构造函数"
ts 复制代码
class Warrior extends Player {
  defense?: number; // 战士独有的属性:防御伤害值
  constructor(props: WarriorProps) {
    super(props); // 调用父类的构造函数,传递参数
    this.defense = props.defense ?? 0; // 初始化 Warrior 类独有的属性
  }
  defend() {
    console.log(`${this.name}独有的技能:开启盾牌防御`);
  }
}

class Shooter extends Player {
  shootRange?: number; // 射手独有的属性:射程
  constructor(props: ShooterProps) {
    super(props); // 调用父类的构造函数,传递参数
    this.shootRange = props.shootRange ?? 0; // 初始化 Shooter 类独有的属性
  }
  shoot() {
    console.log(`${this.name}独有的技能:射击`);
  }
}

自此,子类 Warrior、Shooter 已创建完成

创建子类实例并测试

ts 复制代码
const warrior1 = new Warrior({
  name: 'WarriorA',
  health: 100,
  damage: 30,
  defense: 15,
});
// 实例 warrior1 使用了 Player 类的通用属性及方法
console.log(`${warrior1.name}的血量:${warrior1.health},伤害值:${warrior1.damage}`);
warrior1.move('left');
warrior1.recover(10);
// 实例 warrior1 使用了 Warrior 类的独有属性及方法
console.log(`${warrior1.name}独有的属性:防御伤害值为${warrior1.defense}`);
warrior1.defend();
// warrior1.shoot(); // 实例 warrior1 无法调用 Shooter 类独有的方法
console.log('----------------');

const shooter1 = new Shooter({
  name: 'ShooterA',
  health: 100,
  damage: 50,
  shootRange: 10,
});
// 实例 shooter1 使用了 Player 类的通用属性及方法
console.log(`${shooter1.name}的血量:${shooter1.health},伤害值:${shooter1.damage}`);
shooter1.move('right');
shooter1.recover(10);
// 实例 shooter1 使用了 Shooter 类的独有属性及方法
console.log(`${shooter1.name}独有的属性:射程为${shooter1.shootRange}`);
shooter1.shoot();
// shooter1.defend(); // 实例 shooter1 无法调用 Warrior 类独有的方法
console.log('----------------');

const warrior2 = new Warrior({});
console.log(`${warrior2.name}的血量:${warrior2.health},伤害值:${warrior2.damage}`);
const shooter2 = new Shooter({
  name: 'ShooterB',
});
console.log(`${shooter2.name}的血量:${shooter2.health},伤害值:${shooter2.damage}`);

输出结果:

顺便提一嘴,vscode 如何运行 ts 文件:

  1. npm 安装 typescriptts-node
bash 复制代码
npm install -g typescript
npm install -g ts-node
  1. 安装 VScode 插件:Code Runner
  1. 保存 ts 文件后点击 VScode 右上角的 Run Code 按钮
相关推荐
前端精髓44 分钟前
移除 Effect 依赖
前端·javascript·react.js
码云之上1 小时前
从一个截图函数到一个 npm 包——pdf-snapshot 的诞生记
前端·node.js·github
码事漫谈2 小时前
AI提效,到底能强到什么程度?
前端·后端
IT_陈寒2 小时前
React hooks依赖数组这个坑差点把我埋了
前端·人工智能·后端
阿祖zu2 小时前
内容创作 AI 透明化声明倡议与项目开源
前端·后端·github
lpfasd1232 小时前
TypeScript + Cloudflare 全家桶部署项目全流程
前端·javascript·typescript
ZC跨境爬虫2 小时前
极验滑动验证码自动化实战:背景提取、缺口定位与Playwright滑动模拟
前端·爬虫·python·自动化
行者-全栈开发2 小时前
腾讯地图 Map Skills 快速入门:从零搭建 AI 智能行程规划应用
人工智能·typescript·腾讯地图·ai agent·mcp 协议·map skills·智能行程规划
前端Hardy2 小时前
字节/腾讯内部流出!Claude Code 2026王炸玩法!效率暴涨10倍
前端·javascript·vue.js
糟糕好吃3 小时前
AI 全流程解析(LLM / Token / Context / RAG / Prompt / Tool / Skill / Agent)
前端·后端·设计模式