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

标签 javascript oop

我正在尝试在 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/

相关文章:

c# - 这个 Composition 是否违反了面向对象编程的任何原则?

c++ - 使用 switch 语句访问函数 OOP C++

c++ - 为什么一个类不能对函数和数据成员具有相同的名称?

javascript - 调整 Blogger 的精选帖子小工具以显示特定标签的最新帖子

javascript - 标题元素内的 i 上的 toggleClass 无法正常工作

javascript - 如何使用 browserify 捆绑多个 javascript 库?

操作大型数据类的多个 "worker classes"的 C++ 模式

java - 无法调用 super.toString

javascript - 有必要在 html() 之前或 innerHTML 之前调用 empty() 吗?

javascript - Node Webkit 程序因 nwdirectory 崩溃