gpt4 book ai didi

javascript - 如何在 Javascript 中访问外部对象上的函数

转载 作者:行者123 更新时间:2023-11-30 10:31:44 25 4
gpt4 key购买 nike

我无法在 FB.api 中调用 method()。我怎样才能访问方法? 做不到 this.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");
}
});

最佳答案

保存对 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
}
});

关于javascript - 如何在 Javascript 中访问外部对象上的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16505224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com