随着 HarmonyOS 的发展,API 版本的更新带来了许多新的特性和限制。在 API 11 及以后的版本中,直接赋值对象的语法不再被支持,这要求开发者们采用新的方式来处理对象的创建和属性的访问。同时,HarmonyOS 支持 ETS(Enhanced TypeScript)文件,这是一种扩展了 TypeScript 的文件格式,用于更好地支持 HarmonyOS 的特性。然而,ETS 文件并不支持所有的 TypeScript 语法特性,这就需要开发者灵活运用不同的文件格式来实现所需的功能。
【完整示例】
src/main/ets/common/FactoryUtil.ts
export function createInstance<T>(constructor: new () => T): T { return new constructor();}
复制代码
src/main/ets/pages/Index.ets
import { createInstance } from '../common/FactoryUtil.ts';
class Person { name: string = '张三';}
class Person2 { name: string = '李四';}
function sum(a: number, b: number) { console.info(`${a} + ${b} = ${a + b}`);}
function subtract(a: number, b: number) { console.info(`${a} - ${b} = ${a - b}`);}
function printString(str: string) { console.info(str);}
class BirthInfo { birthDate: string = "2020-02-03";}
class UserInfo { userName: string = ''; birthInfo?: BirthInfo = new BirthInfo(); calculateAge = (): number | string => { if (!this.birthInfo) { return '数据异常'; } const today = new Date(); const birthDate = new Date(this.birthInfo.birthDate); const age = today.getFullYear() - birthDate.getFullYear(); return age; };}
class Action { description: string; action: Function;
constructor(description: string, action: Function) { this.description = description; this.action = action; }}
@Entry@Componentstruct MainPage { @State actions: Action[] = [ new Action('加法计算', sum), new Action('减法计算', subtract), new Action('打印字符串', printString), ];
build() { Column({ space: 10 }) { Button('创建对象并获取属性').onClick(() => { const person: object = Object({ name: '张三', age: 30 }); console.info(`person['name']:${person['name']}`); console.info(`person['age']:${person['age']}`); });
Button('执行动作').onClick(() => { this.actions.forEach(action => { if (action.description.includes('加法')) { action.action(1, 2); } else if (action.description.includes('减法')) { action.action(1, 2); } else if (action.description.includes('打印')) { action.action('Hello World'); } }); });
Button('从TS文件创建实例').onClick(() => { const person1 = createInstance(Person); console.info('person1.name', person1.name);
const person2 = createInstance(Person2); console.info('person2.name', person2.name); });
Button('获取用户信息').onClick(() => { const userInfo = new UserInfo(); Object.keys(userInfo).forEach(key => { console.info(`key: ${key}`); });
console.info(`年龄: ${userInfo.calculateAge()}`); }); } .width('100%') .height('100%'); }}
复制代码
打印
person['name']:张三person['age']:30
1 + 2 = 31 - 2 = -1Hello World
person1.name 张三person2.name 李四
key: userNamekey: birthInfokey: calculateAge年龄: 4
复制代码
技术要点解析
1. 创建对象并获取属性
使用 Object()创建对象并使用索引访问属性,以确保兼容性与正确性。
const person:object = Object({ name: '张三', age: 30 });console.info(`person['name']:${person['name']}`);console.info(`person['age']:${person['age']}`);
复制代码
2. 执行动作
将方法定义为对象属性,并通过动态方式调用它们。
this.actions.forEach(action => { if (action.description.includes('加法')) { action.action(1, 2); } // 其他条件分支...});
复制代码
3. 从 TS 文件创建实例
在某些情况下,ETS 文件不支持特定的 TypeScript 语法特性,如 new () => T 语法。这时可以将这部分逻辑移到 TS 文件中,并在 ETS 文件中导入使用。例如,创建一个通用的工厂函数来实例化类:
const person1 = createInstance(Person);console.info('person1.name', person1.name);
复制代码
4. 遍历对象的属性
可以使用 Object.keys()遍历对象的属性,并利用面向对象的思想通过实例方法计算年龄。
const userInfo = new UserInfo();Object.keys(userInfo).forEach(key => { console.info(`key: ${key}`);});
console.info(`年龄: ${userInfo.calculateAge()}`);
复制代码
结论
本文介绍了 HarmonyOS 应用开发中的几个关键技巧,包括使用 Object()创建对象、动态调用方法、使用 TS 文件中的工厂函数创建实例,以及遍历对象属性。通过遵循良好的命名规范和代码组织结构,可以使代码更加清晰易懂,便于后期维护。掌握了这些技巧后,开发者能够更加高效地开发出高质量的 HarmonyOS 应用程序。
评论