Uederson Posted November 22, 2018 Share Posted November 22, 2018 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 More sharing options...
b10b Posted November 22, 2018 Share Posted November 22, 2018 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 More sharing options...
Uederson Posted November 23, 2018 Author Share Posted November 23, 2018 Friend, it worked! Thank you so much! But now I have another issue: this.btnTest.on('pointerdown', ()=>{ if(this.change == 0){ this.setFrame(0); } }); It gives me "this.setFrame is not a function" edit: btnTest is a sprite. Link to comment Share on other sites More sharing options...
b10b Posted November 23, 2018 Share Posted November 23, 2018 You'll kick yourself. Now "this" is the Scene, therefore ... this.btnTest.setFrame(0); Link to comment Share on other sites More sharing options...
Recommended Posts