簡體   English   中英

Javascript,節點,Q承諾,原型函數和“this”

[英]Javascript, node, Q promises, prototype functions, and “this”

我真的不明白為什么在我的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);
};

你需要綁定你的回調,使他們有正確的this

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

您還可以在構造函數中綁定函數,如下所示:

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

然后像你現在一樣調用函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM