How to work around the ES6 class scope issue with the keyword "this"


This question already has an answer here:

  • How to access the correct `this` inside a callback? 5 answers
  • How do I write a named arrow function in ES2015? 6 answers

For example in the Class constructor:

Socket.on('user:join', onUserJoin);

'onUserJoin' is declared as a method of the class but is being called by so the 'this' is not my Class. A way to resolve this is to use the '=>' function.


Socket.on('user:join', (data)=>{
        this.isOnline = true;

Now 'this' is my class, but how do I reference this anonymous function to unsubscribe ?

socket.removeListener('user:join', ????);

I did try this:

let self;
class RoomController {
    constructor() {
    self = this;

and reference the self in the methods but the self was being shared across sockets...

naming the anonymous function could solve it but I preferred for my case the bind option.

You can use Function.prototype.bind.

Socket.on('user:join', onUserJoin.bind(this));

This ensures that onUserJoin has the correct context, which will be the instance of your class.