How to call "this" game inside function (javascript knobby newb)

So I’m having some trouble adjusting to classes and objects in JS. Sorry for the newb question, but how do I make the call to add an image when I have a function inside Create?
class GameScene extends Phaser.Scene{
constructor(){etc.}
preload(){
this.load.image(‘img’, ‘img.png’);
}
create(){

  function insideCreate(){
        let myImage =   this.add.image(x, y, 'img');  //"this" is undefined. "game" is undefined. "this.game" is   undefined. GameScene.add.image is undefined...
 }

}

}

Hi @casey,
Using arrow function:

create(){
    let myimage;
    let insideCreate = () => {
        myImage =   this.add.image(x, y, 'img');
    }
}

Storing this in a variable:

create(){
    let myimage;
    let t = this;
    function insideCreate() {
        myImage =   t.add.image(x, y, 'img');
    }
}

Regards.

1 Like

Thank you. They sure made JS a whole new level of confusing!

In addition to arrow function and old fix of storing this yet another way is to bind the function to the scene object instead of its own this:

create(){
    function insideCreate() {
        myImage =   this.add.image(x, y, 'img');
    }
    const f = insideCreate.bind(this);
}

There are better parts of the language by avoiding this altogether but it is out of scope here.

1 Like
insideCreate.call(this);
1 Like