微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决检查成员是否已在构造函数中启动

我有一个扩展 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 举报,一经查实,本站将立刻删除。