RESOLVED: forEach this.add.text

Hey all, just getting into game development with Javascript/Phaser and while I’ve been able to google or troubleshoot my own issues up to now, I haven’t been able to figure out the issue below. Can anyone tell me why the this.add.text line in the forEach won’t add text but the test line outside the forEach loop above it works fine? Can someone tell me how to modify? Essentially what I want to do is get a list of inventory and then map out the x, y of where to place it and then add it to a container for later use. Everything I assign outside of a forEach loop gets added fine but I can’t loop through my inventory in order to place them all. In the console when I try the forEach loop I get the following:

Uncaught TypeError: Cannot read property ‘text’ of undefined
at menu.js:207
at Array.forEach ()
at MenuScene.showMainMenu (menu.js:202)
at MenuScene.create (menu.js:13)
at initialize.create (phaser.min.js:1)
at initialize.bootScene (phaser.min.js:1)
at initialize.start (phaser.min.js:1)
at initialize.run (phaser.min.js:1)
at initialize. (world.js:146)
at initialize.h.emit (phaser.min.js:1)

The code is:

    // Does work
    this.add.text(15, 35, 'test').setInteractive()
    all_items.forEach(function(element) {
            name = element[0]
            count = element[1]
            console.log(name + ' x ' + count)
            // Does not work
            this.add.text(15, 40, name).setInteractive()
    })

Thanks all
Scott

Hi,
Try with an arrow function syntax:

element => {
...your code
}

instead of function(element)

1 Like

That did it, thanks very much!

Hi @Scott_Rowley, I know you could work this out but here some more info about it.

This is happening cause of the concept of context of functions. You may check from here.

And the answer @BlunT76 works because arrow functions doesn’t have a context, therefor it’s using the current context (which is scene) in this matter.

So your example could work like this way too when you know u can’t work with arrow functions

var self = this;
all_items.forEach(function(element) {
    name = element[0]
    count = element[1]
    console.log(name + ' x ' + count)
    // Does not work
    self.add.text(15, 40, name).setInteractive()
})

Hope this clearify some for you =)

Or using the forEach second argument, thisArg:

all_items.forEach(function(element) {
    name = element[0]
    count = element[1]
    console.log(name + ' x ' + count)
    // Does not work
    this.add.text(15, 40, name).setInteractive()
}, this) // <== thisArg here determine the context