我在JavaScript
中使用回调函数时有点困惑,例如在执行以下调用时:
func(obj , callback);
并且假设func
发送了一些AJAX
请求,并将对象作为回复,让我们称之为resObj
,我是否需要如果我想在那里使用它,将它传递给回调?谢谢
答案 0 :(得分:0)
例如,在进行
func(obj, callback);
调用时,如果我想在那里使用它,是否需要将结果传递给回调?
不,你没有。调用它时func
会将结果传递给回调,这就是重点。在编写callback
函数时,您只需将其作为参数接受。
function func(o, cb) {
setTimeout(function() { // or ajax request or whatever
const resObj = o.example + 3;
cb(resObj); // here the result is passed to the callback
}, 50);
}
function callback(resObj) {
console.log(resObj);
}
const obj = {example: 38};
func(obj, callback); // You're not *calling* the callback here