gpt4 book ai didi

javascript - 创建一个 Javascript 回调函数?

转载 作者:数据小太阳 更新时间:2023-10-29 05:43:01 24 4
gpt4 key购买 nike

我想知道如何在这段代码中实现回调

MyClass.myMethod("sth.", myCallback);
function myCallback() { // do sth };

var MyClass = {

myMethod : function(params, callback) {

// do some stuff

FB.method: 'sth.',
'perms': 'sth.'
'display': 'iframe'
},
function(response) {

if (response.perms != null) {
// How to pass response to callback ?
} else {
// How to pass response to callback ?
}
});
}

最佳答案

实现“//如何将响应传递给回调?”的三种方式:

  1. callback(response, otherArg1, otherArg2);
  2. callback.call(this, response, otherArg1, otherArg2);
  3. callback.apply(this, [response, otherArg1, otherArg2]);

1 是最简单的,2 是为了防止你想在你的回调函数中控制 'this' 变量的值,3 类似于 2,但是你可以传递可变数量的参数给回调

这是一个不错的引用:http://odetocode.com/Blogs/scott/archive/2007/07/05/function-apply-and-function-call-in-javascript.aspx

关于javascript - 创建一个 Javascript 回调函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5111381/

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