Jump to content

Reference function / variable from inside a function


DomDom
 Share

Recommended Posts

Hey,

how can I access a variable or a function that is declared in create() from a function inside a function ?

For example I have the following code. How can I call my textBtnConnect from makeInteractiveAlt()
 


import Phaser from "phaser";
import io from 'socket.io-client';
import R from '../res.js';
import config from '../../config.json';

export default class Menu extends Phaser.Scene{

    constructor(){
        super(R.scenes.Menu);
    }

    create(){
	this.textBtnConnect = this.add.text(
            this.game.config.width/2,
            this.game.config.height/2,
            'CONNECT'
        );
		
	this.textBtnConnect.on('pointerdown', () => {
		this.textBtnConnect.disableInteractive()
			
		makeInteractive(); // Calling function works
		this.someRandomFunction() // Calling function works
	});
		
		
	function makeInteractive(){
		// TypeError: Cannot read property 'textBtnConnect' of undefined
		this.textBtnConnect.setInteractive()
		// Uncaught ReferenceError: textBtnConnect is not defined
		textBtnConnect.setInteractive()
	}
   }

    update(){}

    render(){}

    someRandomFunction(){
		// works
		this.textBtnConnect.setInteractive()
		
		
		makeInteractiveAlt() // Calling function works
        
		function makeInteractiveAlt(){
			// TypeError: Cannot read property 'textBtnConnect' of undefined
			this.textBtnConnect.setInteractive()
			// Uncaught ReferenceError: textBtnConnect is not defined
			textBtnConnect.setInteractive()
		}
    }
	
}
Link to comment
Share on other sites

Hello, in your example I guess you need to use setInteractive() before using .on('pointerdown'...

About your question there are different ways you can do:

Try passing it as arg to the function

function makeInteractive(btn) {  //use btn here... }  and callit like  makeInteractive(this.textBtnConnect)

Or you can use arrow function and use it with 'this'

const makeInteractive = () => { // use this.textBtnConnect here }

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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