简体   繁体   中英

How can we pass one specific variable of a function as a callback?

I have recently picked up callback functions and trying to learn more on it. I wanted to pass c from function y, which is the ultimate sum in function x as a parameter. Can this be done and how so?

function x(y){
    console.log("x");
     y();
}

x(function y(){
    var a = 5;
    var b = 45;
    var c = a+b;
    console.log(c);
});

You can simply return c from y and use it in x like so:

function x(y){
    console.log("x");
    let c = y();
    console.log("c: ", c);
}

x(function y(){
    var a = 5;
    var b = 45;
    var c = a+b;
    console.log(c);
    return c;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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