0
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

2
  • 1
    How much research effort is expected of Stack Overflow users? Commented Jun 11, 2021 at 14:41
  • It can't, that's why you can simulate private state through closures in JS. You can pass it's (current) value to the callback (or in the case of objects, a reference) but not the variable; which means, the callback doesn't "notice" when the value of a changes; all it has is the value given. And you can not change the value of the variable from the callback. If you explain what exactly you are trying to achieve, we can help you work around the problems. Commented Jun 11, 2021 at 14:55

2 Answers 2

4

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); }
});
Sign up to request clarification or add additional context in comments.

Comments

1

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); }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.