This.test is not a function

Hello all,

I’m new to javascript and phaser and I get stuck with something I wouldn’t expect any problem actually.

Here’s a simplified version of my code:

class Game {
    constructor(config = {}) {
        this.phaserConfig = {
            type: Phaser.AUTO,
            parent: config.id ? config.id : "game",
            width: config.width ? config.width : 800,
            heigth: config.height ? config.height : 600,
            scene: {
                key: "default",
                init: this.initScene,
                create: this.createScene,
                update: this.updateScene,
                preload: this.preloadScene
            }
        }
    }

    test(value){
        var val = value;
        console.log("Hello");
    }

    async initScene(data) {
        this.collection = data.collection;
        this.authId = data.authId;
        this.gameId = data.gameId;
        this.ownerId = data.ownerId;
    }

    async preloadScene(){
        this.load.image('sasha', '../assets/sasha.jpg');
    }
    async createScene() {
        this.original_img = this.textures.get('sasha').getSourceImage();
        this.img_avg = this.textures.createCanvas('avg_img', this.original_img.width, this.original_img.height);
        this.add.image(0, 0, 'avg_img').setOrigin(0, 0);

        this.test(1);

    }
}

with that code, I get the following error:Uncaught (in promise) TypeError: this.test is not a function

…and I really don’t get why…I read some tutorials where they call a method inside another method inside the class and there is no problem with that. So here, why my test() is not recognised as a function ?

Here is the code from the tutorial where the method showBalance() is called inside withdraw():

class BankAccount {
    constructor(owner, balance) {
        this.owner = owner;
        this.balance = balance;
    }

    showBalance() {
        console.log("Solde: " + this.balance + " EUR");
    }

    deposit(amount) {
        console.log("Dépôt de " + amount + " EUR");
        this.balance += amount;
        this.showBalance();
    }

    withdraw(amount) {
        if (amount > this.balance) {
            console.log("Retrait refusé !");
        } else {
            console.log("Retrait de " + amount + " EUR");
            this.balance -= amount;
            this.showBalance();
        }
    }
}

Thanks a lot for your answers, this is driving my crazy!

:wave:

The context (this value) for the scene callbacks init() etc. is the scene itself. That’s why this.add.image() is working but this.test() is not.

There are a few ways to handle it but it may be best to write a separate scene class.

1 Like

Thanks! These context/scope can ben tricky sometimes