在使用构造函数时如何访问对象外部的方法?

时间:2014-03-27 01:17:51

标签: javascript object methods constructor trello

我试图获取Trello帐户的成员ID,然后在构造函数中使用该成员ID来生成板。我的问题是我无法访问我在我创建的对象之外返回的成员ID。如何访问TrellloConnect对象外的memberID?

以下是代码:

var TrelloConnect = {
init: function(config) {
    this.config = config;
    this.doAuthorize();
    this.updateLogStatus();
    this.bindLogIn();
    this.bindLogOut();
    this.whenAuthorized();
    this.getMemberID();
},
bindLogIn: function() {
    this.config.connectButton.click(function() {
        Trello.authorize({
            type: "redirect",
            success: this.doAuthorize,
            name: "WonderBoard",
            expiration: "never"
        });
    });
},
bindLogOut: function() {
    this.config.disconnectButton.click(function() {
        var self = TrelloConnect;
        Trello.deauthorize();
        self.updateLogStatus();
    });
},
doAuthorize: function() {
    var self = TrelloConnect;
    self.updateLogStatus();
},
updateLogStatus: function() {
    var isLoggedIn = Trello.authorized();
    this.config.loggedOutContainer.toggle(!isLoggedIn);
    this.config.loggedInContainer.toggle(isLoggedIn);
},
whenAuthorized: function() {
    Trello.authorize({
        interactive: false,
        success: TrelloConnect.doAuthorize
    });
},
getMemberID: function() {
    Trello.members.get("me", function(member) {
        console.log(member.id);
        return member.id;
    });
}
};

 TrelloConnect.init({
    connectButton: $('#connectLink'),
    disconnectButton: $('#disconnect'),
    loggedInContainer: $('#loggedin'),
    loggedOutContainer: $('#loggedout')
});

function Board(memberID) {
    console.log(memberID);
}

var board = new Board(TrelloConnect.getMemberID());

1 个答案:

答案 0 :(得分:0)

Trello.members.get是一个异步函数(即它需要回调而不是返回一个值);如果你想对它提取的数据做些什么,你需要使用回调。

如果您更改getMemberID以接听回电

...
getMemberID: function(callback) {
  Trello.members.get("me", function(member){
    callback(member.id);
  });     
}
...

...然后你可以这样做:

TrelloConnect.getMemberId(function(id){
  new Board(id);
});