2013-05-12 108 views
1

我不能調用FB.api中的method()方法。我如何訪問方法? 不能做到this.method();或方法();如何訪問Javascript中的外部對象的功能

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"); 
    } 
}); 

回答

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 
    } 
}); 
+0

其工作ķ!謝謝!!!! – 2013-05-12 09:23:51

+0

爲此來到這裏。謝謝。 – 2015-03-23 08:23:43

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"); 
    } 
});