Can someone please explain why the following doesn’t work works:
function displayResults(data) {
$("#odNextPage").click(function() {
alert(data.queryType); // "undefined"
return false;
});
}
Why can I use the data object inside the click anonymous function?
Edit: The queryType property wasn’t actually set which I think caused the problem, sorry. I’d still be interested for someone to explain why it now does work, given that the click function is executed outside the scope of the data object.
The thing that calls
displayResultscontrolsdatanot only when the the function is called but also when it returns (and hence before your callback gets called). The calling sequence could look like this:I don’t know the exact circumstances of your situation but the above summarizes what can happen.
When you produce a closure over
datayou’re grabbing ontodatabut that doesn’t mean that you’ve locked what’s insidedata.Now that we know where
datais coming from and why it was broken in the first place, we can consider why it works whendatais correct and left alone.When you create your anonymous callback function:
you’re creating a closure that holds onto a reference to
data(or, more accurately, whatdatapoints to) anddatawon’t be killed off until no one is referencing it. The lifetime of a variable depends on its scope; yourdatavariable has lives within yourdisplayResultsfunction. But the variable only references (or points to) an object in memory and that object will, more or less, stick around until no one references it anymore.The variable name and the object that is named are separate entities with separate lifetimes. To quote Bruce Lee:
You can’t get away from pointers in programming even when they’re not called pointers.