What is 'this'? [scope issue]

And here we go again with something very primary! I have the following test code…

var config = {
    width: 800,
    height: 600,
    type: Phaser.AUTO,
    parent: 'test',
    scene: {
        create: create
    }
};

var game = new Phaser.Game(config);

function create ()
{
    showText();
}

function showText()
{
   this.add.text(15, 15, 'test', { fontFamily: '"Arial"' });
}

Now debugger says “cannot read property ‘text’ of undefined” where it’s obvious to me that the issue is the scope (it doesn’t know what is ‘this’). I tried to replace ‘this’ with ‘window’ and ‘document’ but still no luck.

What the scope ‘this’ refers to here? And what would be the correct reference to use within functions?

Thanks!

In your showText function, ‘this’ should be referring to the Scene, which is how you call/access most Phaser methods. ‘add’ is the Phaser GameObjectFactory, which is how you create game objects within that scene. If ever in doubt regarding context, use console.log.

In your example you could either pass the scene to your showText function, or make showText a method of the scene.

1 Like

Or,

showText.call(this); // this here is a scene instance

Reference: Function.prototype.call()

Thank you very much! Passing ‘this’ as parameter did the trick!

showText(this);

function showText(scope)
{
   scope.add.text(15, 15, 'test', { fontFamily: '"Arial"' });
}

https://github.com/samme/phaser3-faq/wiki#how-do-i-use-this-in-a-scene

For posterity.