7

I'm new to Javascript and want to make simple games with Phaser 3, and I found that Javascript seems to be a little different from other OOP languages like C++ or Java. I checked out the tutorial in the official website and some other tutorial page, most of the code is like:

var config = {
    ...
    scene: {
        preload: preload,
        create: create,
        update: update
    }
}
var game = new Phaser.Game(config)

function preload(){
    this.load.img(...)
}

My question is what is the ‍"this" in the preload() indicate to? Is it means the "game" we defined before?

And how to check the object's class in console? typeof() only tells "object".

kevinHuang
  • 135
  • 1
  • 7
  • Take a look at https://www.w3schools.com/js/js_function_invocation.asp. It explained `this` concept simple – bahman parsamanesh Aug 12 '18 at 09:32
  • 2
    Possible duplicate of [How does the "this" keyword work?](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – mpm Aug 12 '18 at 11:07

3 Answers3

4

this is an instance of Phaser.Scene and not Phaser.Game.
The other answers are incorrect. The code is running the browser.

To see the docs for a Scene you can look here

AturSams
  • 6,416
  • 14
  • 53
  • 91
2

In the code you have this is a pointer to your game instance which is why you can call Phaser methods to load assets, adjust the camera, etc.

In your config you are setting which function is called during the preload step in the game. When Phaser runs it calls your function (which just happens to be named preload too) and sets the scope of this to the game instance.

scunliffe
  • 57,883
  • 24
  • 118
  • 156
  • 2
    This assignment of `this` happens kind of implicitly in this case because Phaser's orchestration happens behind the scenes, you don't "see" the caller of `preload` in your custom code other than defining it as something Phaser can call in the `config`. – MattTreichel Jun 04 '19 at 02:08
0

The value of this depends on the scope of the function. In this case, and assuming this code is running in the browser, then this is equal to the window object.

this should be equal to the value that owns this code.

Reading

christopher
  • 24,892
  • 3
  • 50
  • 86