HarmonyOS应用开发实战:猫猫大作战-constructor 构造器与初始化
前言在 ArkTS 中constructor是类的构造器方法在创建实例时自动调用用于初始化成员变量。在「猫猫大作战」的GameEngine中构造器初始化棋盘数组、计分器和定时器状态。一、构造器基础export class GameEngine { private board: (Cat | null)[][]; private score: number; private combo: ComboInfo; private gameLoopTimer: number; private spawnTimer: number; constructor() { // 初始化 5×8 空棋盘 this.board Array.from( { length: GameConfig.BOARD_HEIGHT }, () Array(GameConfig.BOARD_WIDTH).fill(null) ); this.score 0; this.combo { count: 0, multiplier: 1, lastMergeTime: 0 }; this.gameLoopTimer -1; this.spawnTimer -1; } }二、带参数的构造器export class Cat { id: string; level: CatLevel; x: number; y: number; falling: boolean; constructor(id: string, level: CatLevel, x: number, y: number, falling: boolean false) { this.id id; this.level level; this.x x; this.y y; this.falling falling; } } // 使用 const cat new Cat(cat_001, CatLevel.SMALL, 2, 0, true); console.info(cat.level); // CatLevel.SMALL三、默认值与简写export class GameConfig { static readonly BOARD_WIDTH 5; static readonly BOARD_HEIGHT 8; static readonly CELL_SIZE 60; static readonly SPAWN_INTERVAL 1500; // ms static readonly GAME_OVER_ROW 1; }四、最佳实践构造器初始化所有字段避免使用未定义变量默认参数用设置构造器参数的默认值复杂初始化用方法this.initBoard()提取static 配置GameConfig类集中管理常量五、常见错误错误原因修复字段未初始化声明时未赋值score: number 0构造器太复杂做了 UI 操作构造器只做数据初始化忘记调用 super子类构造器子类必须super()总结构造器是类实例化的入口初始化所有成员变量。核心要点构造器只做数据初始化、 默认参数简化调用、static readonly管理配置常量。如果这篇文章对你有帮助欢迎点赞、收藏⭐、关注你的支持是我持续创作的动力相关资源ArkTS 类与构造器GameEngine 源码第 117 篇strict-type第 119 篇private