gpt4 book ai didi

javascript - Google Data API 上的 OOP Javascript 回调方法

转载 作者:行者123 更新时间:2023-11-30 00:31:15 25 4
gpt4 key购买 nike

我正在尝试在 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 传递当前实例引用方法this作为ManagerhandleAuthResult()里面.

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

关于javascript - Google Data API 上的 OOP Javascript 回调方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29404862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com