Phaser uses this a lot (this.add.image, this.physics.add.sprite, etc.). However, you can only use these things attached to this inside the create or update function. This is very annoying for me because I cannot use this.add.image or this.physics inside a function outside of the update or create function
ex:
//this will not work
function addImage()
{
this.add.image(0, 0, ' ');
}
function create()
{
addImage(); //output: 'this' is not defined in addImage()
}
instead I have to do this:
//this will work
function addImage(place)
{
place.add.image(0, 0, ' ');
}
function create()
{
addImage(this); // adds an empty image in coordinates (0, 0)
}
this is very annoying and inefficient with bigger projects and it would be much easier if this.physics, this.add.image, and all of those were global variables instead of variables stuck in the create and update functions. Is there a workaround to this or something you can do so users do not need to have a choppy solution to using this outside of create or update?
For these examples, when we use this in the create and update functions, the context of the code is referring to the Phaser Scene context that is associated with those two functions. This context is what makes all of those methods available to use (the this.add. and this.physics).
By default, when you provide these two functions to your Phaser Game configuration, Phaser is automatically creating a Phaser Scene instance, and binding the scene context to that method. If you want to use this with the same context, you will need to bind the context of those functions to the same context, or pass the context as an argument (as you did in your example).
Another option would be to create a class that extends the Phaser Scene class, and add the related logic to that class.
For more information on this and how the context works, I would recommend checking out this - JavaScript | MDN.
For an example of how you can bind the same context to another function:
function addImage() {
this.earth = this.add.image(400, 350, "earth");
}
function preload() {
this.load.image("earth", "https://cdn.phaser.io/sandbox/square-earth.png");
}
function create() {
this.addImage = addImage.bind(this);
this.addImage();
}