Javascript, node, Q promises, prototype functions, and "this"


I don't really understand why "this" is undefined in my handleAuthSuccess function, but I imagine it has something to do with it being called by the promise.

Can anyone explain? What is the a proper working way to do something like what I'm trying to accomplish here?

Client.prototype.authenticate = function (email, password) {
    authenticationService.authenticate(email, password).then(this.handleAuthSuccess, this.handleAuthError);

Client.prototype.handleAuthSuccess = function (email) {
    console.log("Credentials verified. Proceeding with login.");
    this.session.auth.isAuthenticated = true; = email;
    var response = { Type: 'login success' };
Problem courtesy of: CodeMonkeyCharlie


You need to bind your callbacks so they have the proper this.

.then(this.handleAuthSuccess.bind(this), this.handleAuthError.bind(this))

You can also bind the functions in your constructor, like this:

this.handleAuthSuccess = this.handleAuthSuccess.bind(this);

and then call the function as you are doing now.

Solution courtesy of: loganfsmyth


There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.