跳至正文
-
Just随手记
Just随手记
  • 首页
  • ArkTS
  • 首页
  • ArkTS
关

搜索

  • bilibili
ArkTS

类

作者 LiuSiyv
2026年5月9日 2 分钟阅读
0

定义类

字段
class 类的名称 {
    属性1: string;
    属性2: number;
    属性3: boolean;
    constructor(属性1: string, 属性2: number, 属性3: boolean) {
        this.属性1 = 属性1;
        this.属性2 = 属性2;
        this.属性3 = 属性3;
    }
}
方法
  • 实例方法只能通过实例调用,可以读取实例字段
  • 静态方法只能通过类调用,只能读取类的字段
class 类的名称 {
  属性1: number;
  属性2: string;
  constructor(属性1: number, 属性2: string) {
    this.属性1 = 属性1
    this.属性2 = 属性2
  }
  // 实例方法
  方法1() {
    console.log("方法1")
    console.log(this.属性2)
    return this.属性1
  }
  // 静态方法
  static 方法2() {
    console.log("方法2")
  }
}

// 调用实例方法
const 实例 = new 类的名称(100, "属性2")
实例.方法1()
// 调用静态方法
类的名称.方法2()
类继承示例
// 父类
class Farther {
  a: string

  constructor(a: string) {
    this.a = a
  }
}

// 子类
class Son extends Farther {
  b: number

  constructor(a: string, b: number) {
    super(a)
    this.b = b
  }
}

使类属性具有被观测变化的能力

有且只有被@ObservedV2的类中被@Trace装饰的属性可以被观测到

嵌套类场景
以下代码中,属性a能被观测,其他属性不能被观测
@ObservedV2
class Father {
  @Trace public a: number
  b: string

  constructor(a: number, b: string) {
    this.a = a
    this.b = b
  }
}

class Son {
  c: number
  d: string
  father: Father

  constructor(c: number, d: string, father: Father) {
    this.c = c
    this.d = d
    this.father = father
  }
}
继承类场景
以下代码中,属性a能被观测,其他属性不能被观测
// 父类
@ObservedV2
class Farther {
  @Trace public a: number
  b: string

  constructor(a: number, b: string) {
    this.a = a
    this.b = b
  }
}

// 子类
class Son extends Farther {
  c: number
  d: string

  constructor(a: number, b: string, c: number, d: string) {
    super(a, b)
    this.c = c
    this.d = d
  }
}
以下代码中,属性a和属性c能被观测其他属性不能被观测
// 父类
@ObservedV2
class Farther {
  @Trace public a: number
  b: string

  constructor(a: number, b: string) {
    this.a = a
    this.b = b
  }
}

// 子类
@ObservedV2
class Son extends Farther {
  @Trace public c: number
  d: string

  constructor(a: number, b: string, c: number, d: string) {
    super(a, b)
    this.c = c
    this.d = d
  }
}
作者

LiuSiyv

关注我
其他文章
上一个

世界,您好!

暂无评论!成为第一个。

发表回复 取消回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关于本站

这里也许是个介绍您自己的好地方,也能介绍您的站点或放进一些工作人员名单。

搜索

近期文章

  • 类
  • 世界,您好!

bilibili

关于本站

这里也许是个介绍您自己的好地方,也能介绍您的站点或放进一些工作人员名单。

近期文章

  • 类
  • 世界,您好!

归档

  • 2026 年 5 月 (2)

bilibili

鄂ICP备2026022733号-1