这个问题比较抽象,实际上我也没有完全弄明白。
有这样一个父类:
export default abstract class Node<Config extends NodeConfig = NodeConfig> {
// ……
abstract node!: Konva.Node
constructor(config?: Partial<Config>) {
// 初始化
this.init(config)
}
// 子类实现
// eslint-disable-next-line @typescript-eslint/no-unused-vars
init(_config?: any) {
/** */
}
}
然后有这样一个子类:
export default class Shape<
Config extends ShapeConfig = ShapeConfig
> extends Node<Config> {
declare node: Konva.Shape
init(config: ShapeConfig) {
console.log('shape config: ', config)
this.node = new ReKonva.Shape()
}
}
再有一个子类:
export default class Rect extends Shape<RectConfig> {
declare node: Konva.Rect
init() {
this.node = new ReKonva.Rect({})
}
}
问题来了,new Rect() 返回的实例的 node 属性是 undefined,但在 int 里直接打印 this.node 是存在的,但打印 this 就是不存在 node。
对于底层原理我还不是很了解,但在将 Node 的 abstract node 改成非抽象属性(去掉 abstract)之后问题就解决了。
总之,抽象类/属性还是不要随便用了。