检查成员是否已在构造函数中启动

问题描述

我有一个扩展 PIXI.Text 的类,它覆盖了认的 this.text,如下所示:

    set text(newText: string) {
        super.text = newText
        this.updatetoolTipText(newText)
    }

问题在于:

  1. set text 在类的构建过程中被调用
  2. this.udpatetoolTipText()使用this.width来调整容器大小

但是在类的构造过程中调用时,this.width 尚未定义并抛出此错误

TypeError: null is not an object (evaluating 'style.styleID')

我已经尝试过 if(this.width == undefined) returnif(this.width == null) return,但似乎没有什么可以阻止触发此错误。构造完成后,类的行为符合预期,这只是在构造过程中抛出。

我通过创建一个虚拟变量在构造期间返回来绕过这个解决方案,但我只是不明白如何/为什么我不能在不抛出错误的情况下检查 this.width 是否存在。

编辑:在下面添加代码片段。

export class TextView extends PIXI.Text {

    constructor(text: string,x: number,y: number,w: number,h: number,container: PIXI.Container,fontSize: number = GameFont.Size.normal,color: string = GameColor.getColor(GameColor.Color.Gray0),centerY: boolean = true) {
        super(text)

        // more irrelevant code below
    }

}

遵循 super 路径导致 this.text 被更新。被调用函数如下所示:

    private updatetoolTipText(newText: string) {
        // if(this.width == null) return // <= this doesn't help
        // if(this.width == undefined) return // <= this also doesn't help
        if(this.width < this.initialW) return  // <= error is being triggered in this line during construction. When I remove this line the class constructs without errors but then the code doesn't work the way it's supposed to.

        // more irrelevant code below
    }


解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)