1

I created this class User:

class User {
    constructor(socket) {
        this.socket = socket;
        this.socket.on('disconnect', this.onDisconnect);
        this.room = 'test';
    }

    onDisconnect () {
        console.log('socket disconnected');
        console.log(this);
    }
}

It has a method onDisconnect and a property room.

In the onDisconnect method this is the socket object. How can I reference other class properties? Specifically this.room

Anthony
  • 1,667
  • 2
  • 17
  • 28
  • Create `onDisconnect()` using the arrow function syntax: `onDisconnect = () => { ... }` – Derek Mar 08 '18 at 01:55
  • `this.socket.on('disconnect', (...args) => this.onDisconnect(...args));` –  Mar 08 '18 at 01:55

1 Answers1

0

You can use function bind method like

this.socket.on('disconnect', this.onDisconnect.bind(socket));