如何在Javascript中访问外部Object上的函数

时间:2013-05-12 07:44:11

标签: javascript cocos2d-html5

我不能在FB.api中调用method()。我该如何访问方法?  不能这样做.method();或方法();

var MyLayer = cc.Layer.extend({
   init: function(){
      FB.init({
       ............
      });
      FB.getLoginStatus(function(response) {
         if (response.status === 'connected') {
               FB.api('/me', function(response) {
                  this.method(); // <---- I cant call this here. How can I call method(); ?? Thank!
               });
         }
      });
   },
   method: function(){
      alert("Hello");
   }
});

2 个答案:

答案 0 :(得分:4)

保存对this的引用并使用:

var MyLayer = cc.Layer.extend({
   init: function(){
       var that = this; // Save reference to context
       //.....
       FB.getLoginStatus(function(response) {
           if (response.status === 'connected') {
               FB.api('/me', function(response) {
                  that.method(); // Call method on stored context
               });
           }
        });
    }
});

或者你可以bind回调函数到上下文(需要ES5):

var MyLayer = cc.Layer.extend({
   init: function(){
       //.....
       FB.getLoginStatus(function(response) {
           if (response.status === 'connected') {
               FB.api('/me', function(response) {
                  this.method(); // Call method on context
               }.bind(this)); // Bind callback to context
           }
        }.bind(this)); // Bind callback to context
    }
});

答案 1 :(得分:0)

尝试:

var MyLayer = cc.Layer.extend({
   init: function(){
      FB.init({});
      FB.getLoginStatus(function(response) {
         if (response.status === 'connected') {
               FB.api('/me', function(response) {
                  MyLayer.method(); 
               });
         }
      });
   },
   method: function(){
      alert("Hello");
   }
});