类
定义类
字段
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
}
}