How to get around the problem of defining an ES6 class with the keyword 'this'

For example, in the class constructor:

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

'onUserJoin' is declared as a class method, but socket.io is called, so 'this'it is not my class. The way to solve this problem is to use the function '=>'.

Example:

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

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

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

I tried this:

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

and refer to self in methods, but itself was split between sockets ...

Naming an anonymous function can solve it, but I preferred the binding option for my case.

+4
source share
2 answers

You can use Function.prototype.bind.

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

, onUserJoin , .

+2

.

,

class RoomController {

    constructor() {
        this.flag = true;
    }

    // Assign the arrow function to the name `setFlag`
    setFlag = (v) => this.flag = v;
}

let r = new RoomController();

function tester(func) {

    func(false);
    console.log(r.flag);
    // false

    func(true);
    console.log(r.flag);
    // true

}

// Now you can pass the function around, `this` will still refer the object `r`
tester(r.setFlag);
+2

All Articles