I have two classes in a function and for some reason in the second function this
is not being recognised correctly.
The classes are Emitter
and Receiver
.
I am trying to figure out why this
is not being picked up correctly here. The log is included in the code below:
const chat = (messages) => {
class Emitter {
constructor(messages = []) {
this.messages = messages;
this.event = () => {};
}
setEvent(fn) {
this.event = fn;
}
trigger() {
this.messages.forEach(message => this.event(message));
}
}
class Receiver {
constructor() {
this.messages = [];
// this prints correctly here
---> Receiver { messages: [] }
console.log('this ===> ', this)
}
ping(message) {
console.log('this ===>', this)
// this here prints the following
this ===> Emitter {
messages: [ 'Hi', 'Hola', 'Bonjour', 'Hi' ],
event: [Function: ping] }
this.messages.push(message);
}
}
const myReceiver = new Receiver();
const myEmitter = new Emitter(messages);
myEmitter.setEvent(myReceiver.ping);
myEmitter.trigger();
return myReceiver.messages;
};