Scope of this in update function

Hi, I’m new to phaser and I have a little trouble with accessing “this” outside of the create function.
I have read Phaser3 + ES6 classes : how to keep the scope from create to update, and used google, but I can’t find a way to make things work.
Here is my problem:
inside the update function, I’d like to iterate over a group, but I lose the “this” refering to the scene:

Here is the main part:

 var config = {
         ...
         scene: {
             create: create,
             preload: preload,
             create_car: create_car,
             update:update
         }
};
...

var game = new Phaser.Game(config);
...
function create_car(x){
     console.log(this); //window if called from iterate udpate, scene if called from create or in update, before iterate
     newcar= this.physics.add.image(x, 200, 'police'); //so this will work or not depending of when it is called
     ...
     return newcar;
 }
         
     function update(){
         
         console.log(this); //scene
         //create_car(100); // "this" in create_car is "window"
         //create_car.call(this, 100); //ok, "this" in create_car is "scene", physics.add works
         cars.children.iterate(function(car){
             if(car && car.y>400){
                 console.log(this); //window, so none of the things I try below will work
                 this.physics.add.image(x, 200, 'police'); // Cannot read property 'add' of undefined
                 //newcar = create_car.call(this, car.x); //does not work
                 newcar = this.create_car.call(this,car.x); //does not work either
                 cars.add(newcar);
                 cars.remove(car,true,true);
             }
         });
     }

My question is: how can I refer to the scene in the create_car function (I thought that game.physics.add… could work, but no), and how do I make this work in the anonymous function in iterate

Hello, a couple ways you could fix this:

cars.children.iterate(function(car){
}.bind(this));

or

cars.children.iterate((car)=>{
});
1 Like