写点什么

🌟 HarmonyOS NEXT:构造器与面向对象全攻略 🌟

作者:Turing_010
  • 2025-06-07
    广东
  • 本文字数:2142 字

    阅读完需:约 7 分钟

🌟 HarmonyOS NEXT:构造器与面向对象全攻略 🌟

##Harmony OS Next ##Ark Ts ##教育


本文适用于教育科普行业进行学习,有错误之处请指出我会修改。



🏗️ 构造器四式

1️⃣ 基础构造器

class Point {  x: number = 0;  // 自动初始化  y: number = 0;    constructor(x: number, y: number) {    this.x = x;    this.y = y;  }}const p = new Point(3, 4); // 坐标(3,4)
复制代码

2️⃣ 继承构造器(super 必杀技)

class Animal {  constructor(public name: string) {}  // 参数属性简写}
class Cat extends Animal { constructor(name: string) { super(name); // 🚨 必须第一行! }}
复制代码

3️⃣ 重载构造器(智能适配)

class Config {  constructor(path: string);        // 签名1  constructor(settings: object);    // 签名2  constructor(value: string | object) {  // 实现    // 初始化逻辑  }}
new Config('app.json'); // 调用签名1new Config({ theme: dark }); // 调用签名2
复制代码

4️⃣ 默认构造器(懒人福音)

class DefaultDemo {  value = '默认值';}
const demo = new DefaultDemo(); // 自动初始化
复制代码



🔒 访问控制三剑客


class BankAccount {  private _balance = 0;  // 私有财产    public get balance() {  // 公开查询    return this._balance;   }}
复制代码



🎨 对象字面量妙用

快速实例化

class User {  name!: string;  age!: number;}
// 直接赋值超方便!const user: User = { name: '小明', age: 18};
复制代码

Record 类型神器

// 创建类型安全的字典const studentScores: Record<string, number> = {  '张三': 95,  '李四': 88};
// 自动提示key和value类型!studentScores['王五'] = 92;
复制代码



🧩 抽象类 vs 接口


// 抽象类示例abstract class Shape {  abstract area(): number;  // 抽象方法}
// 接口示例interface Drawable { draw(): void;}
复制代码



🌐 泛型黑科技

基础泛型类

class SmartBox<T> {  constructor(public content: T) {}    getContent(): T {    return this.content;  }}
// 使用示例const numBox = new SmartBox<number>(42);const strBox = new SmartBox('Hello'); // 自动类型推断
复制代码

泛型约束(类型安检)

interface HasLength {  length: number;}
function logLength<T extends HasLength>(item: T) { console.log(item.length); // 安全访问length属性}
logLength('文本'); // ✅ 3logLength([1,2,3]); // ✅ 3
复制代码

泛型默认值(贴心备胎)

class Pagination<T = string> {  data: T[] = [];}
const page1 = new Pagination(); // 默认string类型const page2 = new Pagination<number>(); // 指定number类型
复制代码



🚀 最佳实践流程图

定义类结构 → 选择访问修饰符 → 设计构造器继承体系规划 → 使用抽象类/接口 → 实现多态引入泛型 → 添加约束 → 提升代码复用
复制代码




🎉 现在就去打造你的 ArkTS 对象世界吧! 遇到面向对象难题随时回来查秘籍~ 😘


🌟 空安全与模块系统完全指南 🌟



🚨 空安全四重防护

1️⃣ 默认非空(安全卫士🛡️)

let name: string = null;    // ❌ 编译报错let age?: number = null;   // ✅ 合法声明
复制代码

2️⃣ 非空断言(危险操作⚠️)

class User {  name!: string;  // 🚀 断言非空}
function getUsername(user: User | null) { return user!.name; // 运行时可能崩溃!}
复制代码

3️⃣ 空值合并(优雅备胎✨)

const config = {  timeout: null ?? 3000  // 超时默认为3秒};
复制代码

4️⃣ 可选链(安全导航🚦)

const user = {  profile?: {    social?: {      wechat?: '小明'    }  }};
console.log(user.profile?.social?.wechat); // 安全访问
复制代码



📦 模块系统全解析

静态导入(常规操作)

// 方式一:整体导入import * as Utils from './math';
// 方式二:精准导入import { PI, calculateArea } from './math';
复制代码

动态导入(按需加载⚡)

// 异步加载提升性能async function loadModule() {  const { encrypt } = await import('./crypto');  encrypt('data');}
复制代码

HarmonyOS SDK 接入

// 方式一:精准导入Kitimport { UIAbility } from '@kit.AbilityKit';
// 方式二:批量导入import * as AbilityKit from '@kit.AbilityKit';
复制代码



🔑 关键字 this 生存指南

正确用法(类方法中✅)

class Counter {  count = 0;    increment() {    this.count++;  // ✅ 指向实例  }}
复制代码

禁用场景(踩雷警告💣)

解决方案(绑定技巧🔗)

// 箭头函数自动绑定class Timer {  start = () => {    console.log(this);  // ✅ 始终指向实例  }}
// 显式绑定const boundHandler = this.handler.bind(this);
复制代码



🎯 最佳实践速查表



💡 开发者备忘录

  1. 空安全第一:始终初始化变量,善用???.

  2. 模块化思维:按功能拆分模块,控制导入范围

  3. this 陷阱:类方法外避免使用,回调记得绑定

  4. 动态加载:超过 50KB 的模块建议动态导入


// 完美代码示例class SafeLoader {  private cache?: Map<string, string>;    async init() {    const { Cache } = await import('./cache');    this.cache = new Cache() ?? null;  }    getData(key: string) {    return this.cache?.get(key) ?? 'default';  }}
复制代码




🚀 掌握这些技巧,轻松驾驭 ArkTS 开发! 遇到问题记得回来查攻略哦~ 😘


用户头像

Turing_010

关注

还未添加个人签名 2025-05-22 加入

还未添加个人简介

评论

发布
暂无评论
🌟 HarmonyOS NEXT:构造器与面向对象全攻略 🌟_Turing_010_InfoQ写作社区