Returning self properties with event arrow functions?

In the following scenario I create 5 buttons dinamically.

Doing it with a regular function this way…

create() {
	for (var a=1; a<=5; a++) {
	    var mybutton = this.add.image(a*50, 10, '').setInteractive();
	    mybutton.mydata = a;
	    mybutton.on('pointerup', function (e) {
   		console.log(this.mydata);
	    });
	}
}

… since this here refers to the objects itself I can return their own properties with this.mydata.

But what if I try to do the same thing with an arrow function this way:

create() {
	for (var a=1; a<=5; a++) {
	    var mybutton = this.add.image(a*50, 10, '').setInteractive();
	    mybutton.mydata = a;
	    this.mybutton.on('pointerup', (e) => {
		// how to return the property value??
	    });
	}
}

How would I return the properties of the objects in that case since this here is pointing to the parent context (scene)? Or in such specific case there is not a way of doing what I want?

Thanks!

You can change var a; to let a;.

Samme, I understand that let will change the scope of the variable but I still couldn’t see how it will helpe me to RETRIEVE the value of “mydata” from within the click event (I need a way to reference the clicked object itself).

Or in this particular case I just shouldn’t use an arrow function?

:thinking:

Change to const mybutton, etc.

for (let a = 1; a <= 5; a++) {
  const mybutton = this.add.image(a * 50, 10, '').setInteractive();
  mybutton.mydata = a;
  mybutton.on('pointerup', (e) => {
    console.log(mybutton.mydata);
  });
}
1 Like

Ohhhhhhh… It never passed my mind to refer to the object using its own name!

Also const ensures that the value won’t be updated along the loop.

Thanks, it was fantastic!

PS: I am learning how to use arrow functions and I am kind into it.

:blush: