[SOLVED] Ncaught TypeError: Cannot read properties of undefined (reading 'root')

Hello. For some reason I can’t reference “this.app.root”, even though I have it inside my Pawn.prototype.initialize(). Here is my code: (its a work in progress dont judge)

Pawn.prototype.initialize = function() {
    this.entity.element.on('click', function (event) {
        if (this.entity.tags.has("white")) {
        console.log(this.entity.getLocalPosition().x);
        currentPieceClicked = event.element.entity.name;
        console.log('The element ' + this.entity.getLocalPosition() + "a" + ' was clicked.');

        if (Math.round(this.entity.getLocalPosition().x) < 2.999) {
            this.app.root.findByTag("SquareCover").element.opacity = 0;
            var square1 = this.app.root.findByTag(getColumn(Math.round(this.entity.getLocalPosition().z)) + Math.round(getRank(this.entity.getLocalPosition().x)));
            var square2 = this.app.root.findByTag(getColumn(Math.round(this.entity.getLocalPosition().z)) + Math.round(getRank(this.entity.getLocalPosition().x)));
            
            square1.element.opacity = 1;
            square2.element.opacity = 1;
            this.entity.translateLocal(this.entity.right.x, this.entity.up.y + 2, this.entity.forward.z);
        } else {
            if (Math.round(this.entity.getLocalPosition().x) <= 6.9999999999999999) {
                this.entity.translateLocal(this.entity.right.x, this.entity.up.y + 1, this.entity.forward.z);
                console.log(Math.round(this.entity.getLocalPosition().x));
            }
        }

my error is this:

Pawn.js?id=141493357&branchId=e6dbac65-52ca-41c1-a115-b310cb94b49a:50 Uncaught TypeError: Cannot read properties of undefined (reading ‘root’)
at ElementComponent. (Pawn.js?id=141493357&branchId=e6dbac65-52ca-41c1-a115-b310cb94b49a:50:22)
at ElementComponent.fire (playcanvas-1.64.3.js:598:18)
at ElementInput._fireEvent (playcanvas-1.64.3.js:69368:13)
at ElementInput._onElementMouseEvent (playcanvas-1.64.3.js:69273:12)
at ElementInput._handleUp (playcanvas-1.64.3.js:69121:9)

Hi @Lucas_Yu and welcome,

You need to set the right context in your anonymous event callback, so this points to the script instance.

One way to do it, use an arrow function. Replace this:

this.entity.element.on('click', function (event) {

With this:

this.entity.element.on('click', (event) => {

Thanks!