Google Data API上的OOP Javascript回调方法

OOP Javascript callback method on Google Data API

本文关键字:Javascript 回调 方法 OOP 上的 Data API Google      更新时间:2023-09-26

我正试图让我的日历事件阅读器使用javascript OOP。在checkAuth()函数上,当调用handleAuthResult时,可以观察到以下内容。

  1. 当使用this.handleAuthResult时,方法handleAuthResult()中的变量this.config.myvar变为未定义。

  2. 当使用this.handleAuthResult()时,方法handleAuthResult()中的变量authResult变为未定义。

代码:

var config = new Config();
var Manager = new Manager(config);
Manager.checkAuth();
function Config(){
    this.myvar = "this is what i want";
    this.clientId="client id";
    this.scopes="scopes";
}
function Manager(theConfig){
    this.config = theConfig;
}
Manager.prototype = {
    constructor: Manager,
handleAuthResult : function (authResult) {
        console.log(authResult);
        console.log(this.config.myvar);
},
checkAuth : function () {
        console.log("checkAuth()");
        gapi.auth.authorize({client_id: this.config.clientId, scope:    this.config.scopes, immediate: true}, this.handleAuthResult);
    }
}

在回拨handleAuthResult()时,我需要同时使用this.config.myvarauthResult

根据@zerkms的评论,我能够用bind方法解决问题。

我可以使用bind方法传递当前实例,该方法将在handleAuthResult()中称为this作为Manager

checkAuth : function () {
        console.log("checkAuth()");
        gapi.auth.authorize({client_id: this.config.clientId, scope:    this.config.scopes, immediate: true}, this.handleAuthResult.bind(this));
    }
}