HarmonyOS class类对象基础使用

按我们之前的写法

就是

typescript 复制代码
@Entry
@Component
struct Dom {
  p:Object = {
    name: "小猫猫",
    age: 21,
    gf: {
      name: "小小猫猫",
      age: 18,
    }
  }
  build() {
    Row() {
      Column() {
        // @ts-ignore
        Text(this.p.gf.name)
      }
      .width('100%')
    }
    .height('100%')
  }
}

直接用 Object 一层一层往里套

这个结构 其实并不是那么友好 而且编辑器没有那么认可 需要用 // @ts-ignore标识才能通过语法检查

不过 运行到没什么问题

我们可以直接将代码结构改成这样

typescript 复制代码
class Person{
  name: string
  age: number
  gf: Person
  constructor(name: string, age: number,gf?: Person) {
    this.name = name;
    this.age = age;
    this.gf = gf;
  }
}
@Entry
@Component
struct Dom {
  p: Person =new Person(
    '小猫猫',
    21,
    new Person('小小猫猫', 18)
  )
  build() {
    Row() {
      Column() {
        Text(this.p.gf.name)
      }
      .width('100%')
    }
    .height('100%')
  }
}

这是 我们声明的对象结构体 一个class 类型 其中包含3个属性

string字符串类型的 name

number数字类型的 age

gf比较特殊 它是 Person类型 就是我们声明的这个类的类型的 简单说 就是 Person的gf可以再套一个Person对象

然后构造函数

然后 constructor 构造函数 相当于创建对象时 就会触发

然后 它接收 三个参数 分别就是我们的三个属性 然后 给自己的赋值

然后 我们定义一个 Person 类型的 属性 叫 p

第一个参数 name 赋值为 小猫猫

第二个参数 age 赋值为 21

然后 第三个参数 gf 类型是 Person 于是 我们new一个Person对象

这个我们只给了两个参数 name 小小猫猫 age 18

这也间接告诉大家 如果类对象的字段 你不想赋值 直接不传就好了

运行结果如下

相关推荐
一只栖枝2 小时前
华为 HCIE 大数据认证中 Linux 命令行的运用及价值
大数据·linux·运维·华为·华为认证·hcie·it
zhanshuo5 小时前
在鸿蒙里优雅地处理网络错误:从 Demo 到实战案例
harmonyos
zhanshuo6 小时前
在鸿蒙中实现深色/浅色模式切换:从原理到可运行 Demo
harmonyos
whysqwhw11 小时前
鸿蒙分布式投屏
harmonyos
whysqwhw12 小时前
鸿蒙AVSession Kit
harmonyos
whysqwhw14 小时前
鸿蒙各种生命周期
harmonyos
whysqwhw15 小时前
鸿蒙音频编码
harmonyos
whysqwhw15 小时前
鸿蒙音频解码
harmonyos
whysqwhw15 小时前
鸿蒙视频解码
harmonyos
whysqwhw15 小时前
鸿蒙视频编码
harmonyos