鸿蒙应用示例:应用开发中的动态获取属性与调用方法技巧
随着HarmonyOS的发展,API版本的更新带来了许多新的特性和限制。在API 11及以后的版本中,直接赋值对象的语法不再被支持,这要求开发者们采用新的方式来处理对象的创建和属性的访问。同时,HarmonyOS支持ETS(Enhanced TypeScript)文件,这是一种扩展了TypeScript的文件格式,用于更好地支持HarmonyOS的特性。然而,ETS文件并不支持所有的TypeScript语法特性,这就需要开发者灵活运用不同的文件格式来实现所需的功能。
【完整示例】
src/main/ets/common/FactoryUtil.ts
1 2 3 | export function createInstance<T>(constructor: new () => T): T { return new constructor(); } |
src/main/ets/pages/Index.ets
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | 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 @Component struct 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%' ); } } |
打印
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | person[ 'name' ]:张三 person[ 'age' ]:30 1 + 2 = 3 1 - 2 = -1 Hello World person1.name 张三 person2.name 李四 key: userName key: birthInfo key: calculateAge 年龄: 4 |
技术要点解析
1. 创建对象并获取属性
使用Object()创建对象并使用索引访问属性,以确保兼容性与正确性。
1 2 3 | const person:object = Object({ name: '张三' , age: 30 }); console.info(`person[ 'name' ]:${person[ 'name' ]}`); console.info(`person[ 'age' ]:${person[ 'age' ]}`); |
2. 执行动作
将方法定义为对象属性,并通过动态方式调用它们。
1 2 3 4 5 6 | this .actions.forEach(action => { if (action.description.includes( '加法' )) { action.action(1, 2); } // 其他条件分支... }); |
3. 从TS文件创建实例
在某些情况下,ETS文件不支持特定的TypeScript语法特性,如new () => T语法。这时可以将这部分逻辑移到TS文件中,并在ETS文件中导入使用。例如,创建一个通用的工厂函数来实例化类:
1 2 | const person1 = createInstance(Person); console.info( 'person1.name' , person1.name); |
4. 遍历对象的属性
可以使用Object.keys()遍历对象的属性,并利用面向对象的思想通过实例方法计算年龄。
1 2 3 4 5 6 | const userInfo = new UserInfo(); Object.keys(userInfo).forEach(key => { console.info(`key: ${key}`); }); console.info(`年龄: ${userInfo.calculateAge()}`); |
结论
本文介绍了HarmonyOS应用开发中的几个关键技巧,包括使用Object()创建对象、动态调用方法、使用TS文件中的工厂函数创建实例,以及遍历对象属性。通过遵循良好的命名规范和代码组织结构,可以使代码更加清晰易懂,便于后期维护。掌握了这些技巧后,开发者能够更加高效地开发出高质量的HarmonyOS应用程序。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了