Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are variables inside functions visible to callback functions declared inside that function?

I had a colleague ask me why he couldn't access an event parameter from a callback function. Turns out that jquery seems to be setting the event to null after the call finishes and creating a temporary local variable fixed the problem (see below).

Then that got me thinking, why is 'message' even available to the callback. Can someone please explain?

$('some seletor').click({msg: message},function(event){
    alert(event.data.msg); //event.data.msg is not available to the json callback because event is null
    var message = event.data.msg; //message will be available to the callback...why?
    $.getJSON('ajax/test.json', function(data) {
        alert(message); //works ok - why is the message variable visible here at all, should it not have gone out of scope when the above function ended?
        alert(event.data.msg); //will crash, seems that event has been set to null by the framework after the function finished
    });    
});
like image 803
jax Avatar asked Nov 16 '25 10:11

jax


1 Answers

Any variable that exists in a given scope is available to all functions that are defined within that scope. (This is just how scope is defined to work in JS, this part of the language specification is probably a good entry point if you want the nitty gritty of how it is defined).

Since the function expression that defines the callback is inside the function that defines the variable, the variable is available to it.

like image 172
Quentin Avatar answered Nov 19 '25 00:11

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!