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

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

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