Checking if members are initiated yet in constructor

Viewed 49

I have a class that extends PIXI.Text which overrides the default this.text with something like so:

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

The problem is that:

  1. set text gets called during the construction of the class
  2. and this.udpateToolTipText() uses this.width to adjust the container size

BUT when called during the construction of the class, this.width isn't defined yet and throws this error:

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

I've tried if(this.width == undefined) return and if(this.width == null) return but nothing seems to prevent this error from triggering. After construction is complete, the class behaves as expected, this is only being thrown during construction.

I've hacked around this solution by creating a dummy variable to return out during construction but I just don't understand how/why I can't check if this.width exists without throwing the error.

Edit: Adding code snippets below.

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
    }

}

Where following the super trail leads to this.text being updated. The function being called looks like this:

    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
    }


0 Answers
Related