0

I came across the following class definition in Javascript:

  class FakeWebSocket {
  constructor(url) {
    this.url = url;
    console.log('connecting to ' + url);
    let i = 0;
    this.id = setInterval(() => this.triggerMessage(i++), 500);
  }
  
  close() {
    console.log('closing connection to ' + this.url);
    clearInterval(this.id);
  }
  
  addEventListener(name, handler) {
    const listeners = this.listeners = this.listeners || {};
    const handlers = listeners[name] = listeners[name] || [];
    handlers.push(handler);
  } 
  
  addEventListener(name, handler) {
    const listeners = this.listeners = this.listeners || {};
    const handlers = listeners[name] = listeners[name] || [];
    handlers.push(handler);
  }
  
  triggerMessage(msg) {
    const listeners = this.listeners;
    if (listeners) {
      const handlers = listeners['message'];
      handlers.forEach(handler => handler({ target: this, data: JSON.stringify(msg) }))
    }
  }
}
const source = new Observable((observer) => {
  const socket = new FakeWebSocket('ws://someurl');
  socket.addEventListener('message', (e) => observer.next(e));
  return () => socket.close();
});

My problem is with the line :

const listeners = this.listeners = this.listeners || {};

Which I interpret as assigning to the constant listeners, itself to which you assign itself or a new object. It does not make any sense to me. I don't see where this.listeners comes from and what the syntax means. Could anybody clarify it?

tom
  • 91
  • 1
  • 6
  • It sets both `listeners` and `this.listeners` at the same time, either to the value of `this.listeners` or an empty object if it's falsey. In other words, it ensures `this.listeners` is an object and creates a local reference `listeners` to it as well (which is arguably superfluous, but a stylistic choice). – deceze Mar 12 '21 at 13:28
  • the variable `const listeners` is not the same as `this.listeners`. – ASDFGerte Mar 12 '21 at 13:28
  • `this.listeners` is initialized in the very line of code you posted. If it's `undefined`, it will be initialized to an empty object. – Pointy Mar 12 '21 at 13:28

0 Answers0