Jump to content

Variables Inside A function


Uederson
 Share

Recommended Posts

Hi guys! I am very new to the Phaser 3, and I have a little and basic question (I searched in the forum for something similar already).

I have the code:

class sectionOne extends Phaser.Scene {
    constructor ()
    {
     	super('sectionOne');
        this.timerA= 0;
    }
    
    preload()
    {
        ...
    }

    create() 
    {
       this.btnTest.on('pointerdown', function () {console.log(this.timerA)});
        
       console.log(this.timerA);
    }
}

The first console.log(this.timerA) shows undefined, but the second one shows the variable value. How to acess the variable value inside the "this.btnTest.on..."? I tried a lot of ways, but nothing worked for me :(

Thank you in advanced! 

Link to comment
Share on other sites

A commonly encountered issue.  By default the scope of "this" inside any function is that very same function.  So how to get to variables "outside"?

Simplest is to use "arrow functions" to scope it as you intended.  Here's an example of the above using an arrow function where "this" will be scoped to the declaring function.

this.btnTest.on('pointerdown', ()=>{console.log(this.timerA)});

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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