我不能在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");
}
});
答案 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");
}
});