3

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;
};
peter flanagan
  • 9,195
  • 26
  • 73
  • 127

1 Answers1

5

The this depends on the scope where it is called but not the scope it is defined. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this In the call myEmitter.setEvent(myReceiver.ping), only the function ping is passed to the myEmitter, not its scope myReciever. In case if you would like to pass myRevciever scope you can bind it the function call.

myEmitter.setEvent(myReceiver.ping.bind(myReceiver));
vishnu sandhireddy
  • 1,148
  • 1
  • 7
  • 12