我正在尝试在 javascript OOP 中创建我的日历事件阅读器。在 checkAuth()
函数中,调用 handleAuthResult
时会观察到以下情况。
当使用
this.handleAuthResult
时,方法handleAuthResult()
中的变量this.config.myvar
变为未定义。当使用
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.myvar
和 authResult
。
最佳答案
根据@zerkms 的评论,我能够通过 bind
解决问题。方法。
我可以通过 bind
传递当前实例引用方法this
作为Manager
在handleAuthResult()
里面.
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/