简体   繁体   中英

Javascript callback function get parent variable value

function foo(callback){
    var a = 1;
    
    return callback();
}

foo(function(){ 
    if ( a == 1 ) { alert(a); }
});

I try to make a callback can access parent var, but I get undefine

anyone know how to achieve this

Make a an argument and pass it to the callback:

function foo(callback){
    var a = 1;
    
    return callback(a);
}

foo(function(a){ 
    if ( a == 1 ) { alert(a); }
});

Try sending variable "a" in callback function as parameter.

 function foo(callback){ var a = 1; return callback(a); } foo(function(a){ if ( a == 1 ) { alert(a); } });

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