#跟着坚果学鸿蒙#ArkTS 基础知识详解:类的构造函数
·
类声明可以包含用于初始化对象状态的构造函数。
- 默认构造函数:若未定义构造函数,ArkTS 会自动生成无参构造函数,使用字段默认值初始化。
class Point {
x: number = 0;
y: number = 0;
}
const p = new Point(); // 合法,使用默认构造函数
- 参数化构造函数:通过参数初始化字段。
class Rectangle {
width: number;
height: number;
constructor(width: number, height: number) {
this.width = width;
this.height = height;
}
}
- 派生类的构造函数
构造函数函数体的第一条语句可以使用关键字super来显式调用直接父类的构造函数。
class RectangleSize {
constructor(width: number, height: number) {
// ...
}
}
class Square extends RectangleSize {
constructor(side: number) {
super(side, side);
}
}
- 构造函数重载签名
可以通过编写重载签名,指定构造函数的不同调用方式。具体方法是,为同一个构造函数写入多个同名但签名不同的构造函数头,构造函数实现紧随其后。
class C {
constructor(x: number) /* 第一个签名 */
constructor(x: string) /* 第二个签名 */
constructor(x: number | string) { /* 实现签名 */
}
}
let c1 = new C(123); // OK,使用第一个签名
let c2 = new C('abc'); // OK,使用第二个签名
更多推荐



所有评论(0)