I know

I know it’s a old question. Actually you can find tons of questions about ‘this’ pointer of JS on StackOverflow or anywhere else. The dogma is really easy that, ‘this’ points to whoever calls it. But, it’s not until you made a mistake and spent half an hour to figure it out that you can say you truely understand what it really says.

Scenario

I was refactoring my old version NodeJS code to new ES6 syntax (because I really like its symplicity and flexibility). My new version of code looks like:

const authManager = new AuthManager();
class Controller {
    startAuthentication() {
        authManager.getProfile(this.someCallback);
    }
    someCallback() {
        this.onProfileReceived();
    }
    onProfileReceived() {...}
}

Then I got an error:

cannot call `onProfileReceived` of undefined.

Prevailing null-pointer error in JS version.

Solution

My first reaction is like, ‘Impossible’, and start to suspect ES6 since I am not trusting it that much. Then quickly, my bad experience of using ‘this’ told me that the ‘this’ pointer was the suspect.
I did some research and find an answer on StackOverflow, whose snippet perfectly explained the issue here:

var O = {
  foo: function () {
    console.log(this);
  },
  bar: 51
};
O.foo(); // `this` is O, the implicit context, inferred from the object host
var foo = O.foo;
foo(); // `this` is is the global object, or undefined in Strict Mode

As we pass the callback function itself as reference into authManager, it was called inside a totally difference context, which is definitely not the context we referred to. Previously I knew that event listener should be binded with context, but now I found out that every callback which was called under a different context should be binded.
Since where the problem lay had been found, the solution seemed pretty obvious:

authManager.getProfile(this.someCallback.bind(this));

Or bind it with constructor().