Jump to content

Using 'this' instead of game


Faizy
 Share

Recommended Posts

Hey,

 

I know what the word *this* does. However I dont know why so many tutorials use 'this' instead of 'game'(or whatever your objectname is called...let´s just assume it´s called 'game'). See this for example. 

// Variable to store the arrow key pressed
this.cursor = game.input.keyboard.createCursorKeys();

// Create the player in the middle of the game
this.player = game.add.sprite(70, 100, 'player');

// Add gravity to make it fall
this.player.body.gravity.y = 600;

Instead of creating 'var player' he(the guy who wrote this tutorial) creates properties of the object 'game'. 

 

Is there any benefit to doing it like so? Or is it just because it´s OOP?

Link to comment
Share on other sites

calling "game.add.sprite" is Phaser way of creating a sprite object with provided key and at the specified coordinates (x:70, y:100 & key: 'player') in this case. Above function call creates the sprite object and adds it to the game stage so that it is added to the view.

But to keep a reference of the generated and added sprite within the script we store it to a variable " this.player ". Now, we can reference this.player anywhere in our script within the scope.

 

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...