Javascript,节点,Q承诺,原型函数和“this”

时间:2013-12-07 00:28:06

标签: javascript node.js prototype q

我真的不明白为什么在我的handleAuthSuccess函数中未定义“this”,但我认为它与promise的调用有关。

有人可以解释一下吗?做一些像我在这里想要完成的事情的正确工作方式是什么?

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;
    this.session.auth.id = email;
    var response = { Type: 'login success' };
    this.send(response);
};

1 个答案:

答案 0 :(得分:4)

您需要绑定回调,以便它们具有正确的this

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

您还可以在构造函数中绑定函数,如下所示:

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

然后像现在一样调用该函数。