2013-05-12 86 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"); 
    } 
});