繁体   English   中英

在JavaScript中将变量从外部函数传递给回调函数

[英]Passing variables from the external function to the callback function in JavaScript

例如,在进行以下调用时,我对在JavaScript使用回调函数有些困惑:

func(obj , callback);

并假设func发送了一些AJAX请求,并获得了一个对象作为响应,让我们将其resObj ,如果我想在其中使用它,是否需要将其传递给回调? 谢谢

当做一个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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM