I’m having trouble understanding how ‘this’ works in JS/Playcanvas with events. When I call a member function of a ES6+ class directly, ‘this’ points to the instantiated object of the ES6 class. When I make the member function act as a listener to a PC event, ‘this’ suddenly points to the global ‘Application’ object. Is there a way to make it so ‘this’ points to the instantiated object in both cases? Why does this happen in the first place, is it because it could bypass the lifetime of the instantiated object?
Thanks.
constructor(data){
//various constructor code goes here
//
//------
//direct call
this.OnBarModified(character);
pc.events.attach(this);
//make this.OnBarModified member function a listener
pc.app.on('barModified', this.OnBarModified);
}
OnBarModified(modifiedBar) {
//when this is called in the constructor directly, this points to the costumeUI instance that has been instantiated as inspected....
//when this is called as a listener by the 'modifiedBar' event, this points to the global 'Application'.... which is not what i want.
console.log(this.data.name + 'attached to' + modifiedBar + 'may have been modified');
}
}```